将元素添加到数组的数组

Adding element to an array of arrays

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

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

但模型在插入数据库之前排除了外键约束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 App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

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(...)

成功了 谢谢