【发布时间】:2019-12-28 19:23:36
【问题描述】:
我正在尝试使用“role_id”外键为我的用户定义一个角色,该外键引用我的“roles”表的“id”。
迁移运行良好,但是当我尝试注册时出现错误。
迁移用户
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->char('nni', 6);
$table->string('firstname');
$table->string('lastname');
$table->string('email')->unique();
$table->unsignedBigInteger('role_id')->default(1);
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
$table->foreign('role_id')->references('id')->on('roles');
});
}
模型/用户
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'nni', 'firstname', 'lastname', 'email', 'role_id', 'admin', 'password',
];
[...]
public function role()
{
return $this->belongsTo(Role::class);
}
}
迁移角色
class CreateRolesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('roles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('description');
$table->timestamps();
});
}
[...]
}
错误
SQLSTATE[23000]:完整性约束违规:1452 无法添加或更新 >子行:外键约束失败(
projectsms.users,>CONSTRAINTusers_role_id_foreignFOREIGN KEY (role_id) 参考 >roles(id))
如果你知道我的问题出在哪里,请告诉我!
【问题讨论】:
-
注意迁移顺序。如果
users表是在roles表之前创建的,它会在尝试创建时使约束失败。在尝试引用外部表之前,应先创建它们。 -
role_id的值没有引用您的roles表中的条目。roles表中是否有角色 id = 1 ?$table->unsignedBigInteger('role_id')->default(1); -
试过了,得到了这个:
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter tableusers`添加约束users_role_id_foreign外键(role_id)引用roles(id))` -
@N69S 我的角色表中没有 role_id = 1,为什么会有它?
-
@Petoux 因为您将
users表中role_id的默认值设置为1。如果您有没有角色的用户,请将该字段设置为可空$table->unsignedBigInteger('role_id')->nullable();
标签: laravel laravel-migrations