简体   繁体   English

在一对多关系laravel 5中保存多个记录

[英]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 HasOneOrMany.php第221行中的FatalThrowableError:类型错误:传递给Illuminate \\ Database \\ Eloquent \\ Relations \\ HasOneOrMany :: save()的参数1必须是Illuminate \\ Database \\ Eloquent \\ Model的实例,给定数组,在D:\\中调用第237行的e-commerec \\ blog \\ vendor \\ laravel \\ framework \\ src \\ Illuminate \\ Database \\ Eloquent \\ Relations \\ HasOneOrMany.php

What is the problem? 问题是什么?

Ok, let's begin with an example from https://laravel.com/docs/5.4/eloquent-relationships : 好的,让我们从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: 你需要传递一个带有Size对象的数组,简化如下:

$product_id->Size()->saveMany([
    new App\Size(['size' => 1])    
]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM