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?
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.
The “has-many-through” relationship provides a convenient shortcut for accessing distant relations via an intermediate relation.
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.']),
]);
You pass an array with arrays. That's wrong.
You need to pass an array with Size objects, simplified like so:
$product_id->Size()->saveMany([
new App\Size(['size' => 1])
]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With