php - Laravel: Eloquent 关系创造多

标签 php laravel collections eloquent

我有一个 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);

最佳答案

您可以尝试两条路径。

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

使用插入方法:

$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 中提供它们你的 table 。如需了解更多信息,您可以在此处阅读。

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

关于php - Laravel: Eloquent 关系创造多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35212000/

相关文章:

javascript - WordPress主题定制: CSS class not found

collections - 我可以使用 NHibernate Criteria 将实体及其子集合投影到类上吗?

php - 如何在一个 mysql_query 中执行多个 SQL 语句?

php - 使用 MySQL 将 CURDATE() 转换为我的本地日期

php - 使用 apache 2.2.17 安装 PHP 5.3.5 时出现问题(apache 崩溃)

java - 关于自定义对象排序问题的集合二分搜索

java - 当我对 List 进行排序时,它的迭代器会发生什么?

php - Laravel 搜索查询 - 'OR' 和 'AND' 的 SQL 排序破坏了 foreach 循环查询

mysql - mysql 插入时° 的 Utf8 问题

php - 如何解决 Laravel 中的 "CSRF Token Mismatch"