Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save multiple record in one to many relation laravel 5

I'm trying to save multiple records in a one to many relationship. I have two models as following.

Product Model

class Product extends Model
{
    protected $primaryKey = 'product_id';
    public $timestamps = FALSE;

    public function Size(){
        return $this->hasMany('App\Size');
    }

}

Size Model

class Size extends Model
{
    public $timestamps = FALSE;
    protected $fillable = ['product_id','size'];

    public function Product(){
        return $this->belongsTo('App\Product');
    }
}

I want to save the sizes of the product. My controller is

public function store(Request $request){

        $product_id = Products::select('product_id')->orderBy('product_id','desc')->first();

        if($request->size_m) $sizes[] = array("size" => $request->size_m );
        if($request->size_l) $sizes[] = array("size" => $request->size_l);
        if($request->size_s) $sizes[] = array("size" => $request->size_s);

        $product_id->Size()->saveMany($sizes);


    }

But I'm getting the following error

FatalThrowableError in HasOneOrMany.php line 221: Type error: Argument 1 passed to Illuminate\Database\Eloquent\Relations\HasOneOrMany::save() must be an instance of Illuminate\Database\Eloquent\Model, array given, called in D:\e-commerec\blog\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Relations\HasOneOrMany.php on line 237

What is the problem?

like image 314
Mutasim Fuad Avatar asked Mar 27 '17 18:03

Mutasim Fuad


People also ask

What is polymorphic relationship in Laravel?

A one-to-one polymorphic relationship is a situation where one model can belong to more than one type of model but on only one association. A typical example of this is featured images on a post and an avatar for a user. The only thing that changes however is how we get the associated model by using morphOne instead.

Does Laravel have many through relations?

The “has-many-through” relationship provides a convenient shortcut for accessing distant relations via an intermediate relation.


1 Answers

Ok, let's begin with an example from https://laravel.com/docs/5.4/eloquent-relationships:

$post = App\Post::find(1);

$post->comments()->saveMany([
    new App\Comment(['message' => 'A new comment.']),
    new App\Comment(['message' => 'Another comment.']),
]);

Problem

You pass an array with arrays. That's wrong.

Solution

You need to pass an array with Size objects, simplified like so:

$product_id->Size()->saveMany([
    new App\Size(['size' => 1])    
]);
like image 102
schellingerht Avatar answered Oct 09 '22 13:10

schellingerht