繁体   English   中英

Laravel: eloquent 关系创建多

[英]Laravel: eloquent relationship create multi

我有一个 ParentItem model

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

我有这个数组

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

我想将其添加为有很多关系。 所以我可以这样做:

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

有没有办法一次创建所有..? 就像是:

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

你可以试试两条路。

使用saveMany方法:

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

有关详细信息,请阅读此处。

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

使用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);

请记住,在插入created_atupdated_at不会自动插入,如果你在表中有它们,你必须在array提供它们。 有关详细信息,请阅读此处。

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

到目前为止,您可以使用createMany Eloquent 方法来实现此目的。

详细信息: 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