向数组的数组中添加元素



我想在这个数组上调用Model::insert()来一次插入多个数据

"person" => array:2 [▼
0 => array:2 [▼
"name" => "Person 1"
"place" => "Place 1"
]
1 => array:2 [▼
"name" => "Person 2"
"place" => "Place 2"
]
]

,但是Model在将外键约束department_id插入数据库之前将其排除在外。我如何将department_id添加到person数组中的每个数组。除了使用for循环迭代和手动放置之外,还有其他方法吗?

结果数组应该看起来像

"person" => array:2 [▼
0 => array:2 [▼
"department_id" => 1
"name" => "Person 1"
"place" => "Place 1"
]
1 => array:2 [▼
"department_id" => 1
"name" => "Person 2"
"place" => "Place 2"
]
]

更新Person模型和' department_id ';到$fillable数组:

protected $fillable = [
...
'department_id',
];

应该是这样的:

<?php
// app/Models/Person.php
namespace AppModels;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
class Person extends Model
{
use HasFactory;
protected $fillable = [
'name',
'place',
'department_id', // add department_id
];
...
}

我认为这里没有转义循环。您可以在这里使用array_map,但它也在内部运行循环。

Person::insert(array_map(function ($person) {
$person['department_id'] = 1;
return $person;
}, $persons));

解决方案类似于Tim Lewis的评论

$department->people()->insert(...)

但是insert似乎没有自动分配id

$department->people()->createMany(...)

工作谢谢你

相关内容

  • 没有找到相关文章

最新更新