【问题标题】:Laravel: eloquent relationship create multiLaravel:雄辩的关系创造多重
【发布时间】:2016-05-14 17:06:48
【问题描述】:

我有一个 ParentItem 模型

$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);

【问题讨论】:

  • createMany 方法有什么问题?此外,您可以像这样获得父模型:$parentItem = ParentItem::first();。这只会从数据库中检索一项。您现在的做法是获取数据库中的所有条目,然后使用 PHP 获取集合中的第一项。

标签: php laravel collections eloquent


【解决方案1】:

你可以尝试两条路径。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-17
    • 2017-10-16
    • 2012-10-08
    • 2016-11-26
    • 2015-03-14
    • 2018-11-28
    相关资源
    最近更新 更多