我正在尝试使用“ role_id”外键为我的用户定义一个角色,该外键引用我的“角色”表的“ 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_foreign
FOREIGN KEY(role_id
)参考>roles
(id
))
如果您知道我的问题在哪里,请告诉我!
答案 0 :(得分:0)
由于您的结构取决于每次使用都必须有一个角色这一事实,因此您应该在迁移中包括插入默认角色。
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();
});
DB::table('roles')->insert([
'id' => 1, //must be 1
'name' => 'default',
'description' => 'default role (just registered)',
'created_at' => \Carbon\Carbon::now(),
'updated_at' => \Carbon\Carbon::now(),
]);
}
[...]
}