insert `id` autoincrement primary key field explicitly in laravel 5.2

折月煮酒 提交于 2020-07-09 06:27:06

问题


I am migrating an old data into laravel.

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

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

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

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

Is it even possible in there?


回答1:


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.

So have that variable like:

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)



来源:https://stackoverflow.com/questions/35253153/insert-id-autoincrement-primary-key-field-explicitly-in-laravel-5-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!