在Laravel 5.2中显式插入`id`自动增量主键字段 [英] insert `id` autoincrement primary key field explicitly in laravel 5.2

查看:236
本文介绍了在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)

这篇关于在Laravel 5.2中显式插入`id`自动增量主键字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆