简体   繁体   English

Laravel: eloquent 关系创建多

[英]Laravel: eloquent relationship create multi

i have a ParentItem model我有一个 ParentItem model

$parentItem = ParentItem::get()->first();

I have this array我有这个数组

$items = array(
 array(
  'title' => 'test1',
  'desc' => 'test1'
 ),
 array(
  'title' => 'test2',
  'desc' => 'test2'
 )
);

i want to add it as a has many relationship.我想将其添加为有很多关系。 so i can do:所以我可以这样做:

foreach($items as $item) {
 $parentItem->items()->create($item)
}

is there any way way to create all at once..?有没有办法一次创建所有..? something like:就像是:

$parentItem->items()->createMany($items);

You can tryout two path. 你可以试试两条路。

Using saveMany method: 使用saveMany方法:

$parentItem = ParentItem::first();
$items = array(
    new Item(['title' => 'test1','desc' => 'test1']),
    new Item(['title' => 'test2','desc' => 'test2'])
);
$parentItem->items()->saveMany($items)

For further info you can read here. 有关详细信息,请阅读此处。

https://laravel.com/docs/5.1/eloquent-relationships#inserting-related-models https://laravel.com/docs/5.1/eloquent-relationships#inserting-related-models

Using insert method: 使用insert方法:

$parentItem = ParentItem::first();
$items = array(
    array('title' => 'test1','desc' => 'test1','parent_item_id' => $parentItem->id),
    array('title' => 'test2','desc' => 'test2','parent_item_id' => $parentItem->id)
);
Item::insert($items);

Remember in insert created_at and updated_at won't be inserted automatically, you have to provide them in the array if you have them in your table. 请记住,在插入created_atupdated_at不会自动插入,如果你在表中有它们,你必须在array提供它们。 For further info you can read here. 有关详细信息,请阅读此处。

https://laravel.com/docs/5.1/queries#inserts https://laravel.com/docs/5.1/queries#inserts

As of right now, you may use the createMany Eloquent method to achieve this.到目前为止,您可以使用createMany Eloquent 方法来实现此目的。

Details here: https://laravel.com/docs/9.x/eloquent-relationships#the-create-method详细信息: https://laravel.com/docs/9.x/eloquent-relationships#the-create-method

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

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