如何在表Laravel Eloquent中保存许多记录(无关系)

时间:2019-01-30 07:55:30

标签: laravel eloquent

我希望能够在一个表的一行中保存很多行,我已经阅读到可以使用create方法来完成此操作,但是在尝试使用该方法时却遇到了这个错误

  

SQLSTATE [HY000]:常规错误:1364字段'名称'没有默认值(SQL:插入person_rolesupdated_atcreated_at)值(2019- 01-30 07:46:19,2019-01-30 07:46:19))

我的代码

    $data = [
        ['name' => 'actor'],
        ['name' => 'translator'],
        ['name' => 'director'],
        ['name' => 'stageDirector'],
        ['name' => 'costume'],
        ['name' => 'musical'],
        ['name' => 'supportDirector'],
        ['name' => 'photographer'],
        ['name' => 'choreographer'],
    ];

    $personRoles = PersonRole::create($data);

我使用Laravel v5.7.21

已更新,在我的PersonRole中,我已添加此行

protected $fillable = ['name'];

为了让大量分配工作,但我仍然遇到错误。

3 个答案:

答案 0 :(得分:1)

您必须使用insert()方法,但是使用插入方法时,必须手动插入created_atupdated_at

$data = [
    [
        'name' => 'actor',
        'created_at' => now(),
        'updated_at' => now(),
    ],
    ['name' => 'translator'],
    ['name' => 'director'],
    ['name' => 'stageDirector'],
    ['name' => 'costume'],
    ['name' => 'musical'],
    ['name' => 'supportDirector'],
    ['name' => 'photographer'],
    ['name' => 'choreographer'],
];

$personRoles = PersonRole::insert($data);

答案 1 :(得分:1)

您必须使用insert而不是create-

$personRoles = PersonRole::insert($data);

答案 2 :(得分:0)

更新:

以您的情况

foreach($data as $datas){PersonRole::create(['name'=>$datas->name])}

$now = Carbon::now()->toDateTimeString();
PersonRole::insert([
    ['name'=>'Foo', 'created_at'=>$now, 'updated_at'=>$now],
    ['name'=>'Bar', 'created_at'=>$now, 'updated_at'=>$now],
    ['name'=>'Baz', 'created_at'=>$now, 'updated_at'=>$now],
    ..................................
]);

或在模型类中创建函数并调用

public function createManyRecord(array $records){
    foreach ($records as $record) {
        $this->create($record);
    }
    return $this;
}