在Laravel 5.2中显式插入`id`自动增量主键字段

在Laravel 5.2中显式插入`id`自动增量主键字段

问题描述:

我正在将旧数据迁移到laravel中.

I am migrating an old data into laravel.

我想要的是在新表中保持以前的ID不变 我有一个默认的$table->increments(id)字段.

What i want is to keep the previous ids same in the new table where i have a default $table->increments(id) field.

在laravel中有一种方法可以明确插入此id字段吗?

Is there a way in laravel that i can explicitly insert this id field?

由于我无法使用雄辩的模型create方法来做到这一点:

As i am unable to do it using eloquent model create method :

User::create([
'id' => 123456,
'first_name' => 'john',
'last_name' => 'doe'
])

里面甚至有可能吗?

问题必须出在用户模型中.打开User.php文件并修改$fillable变量.将id添加到数组. $fillable变量告诉Eloquent像您正在做的那样,让Eloquent保护哪些字段免受质量分配(质量分配意味着您要一次在插入中设置所有值).因此,即使您像在create()调用中那样指定了id,Eloquent也将忽略您设置的任何值,因为该字段不是$fillable字段的一部分.

The problem must be in the User model. Open the User.php file and modify the $fillable variable. Add id to the array. The $fillable variable tells Eloquent which fields to protect from a mass-assignment like the one you are doing (mass assignment meaning you're setting all the values at once in your insert). So even if you specify id like you did in your create() call Eloquent will ignore whatever value you have set because that field is not part of the $fillable fields.

所以有这样的变量:

protected $fillable = ['id', 'first_name', 'last_name'];

protected $fillable = ['id', 'first_name', 'last_name'];

您应该会很好(还要考虑到您没有将任何字段留空,根据用户迁移,该字段不能为空)

and you should be good to go (also taking into account that you have not left any fields empty which according to the user migration cannot be null)