为用户角色使用外键时违反完整性约束

Integrity constraint violation when using a Foreign key for a user role

我正在尝试使用 "role_id" 外键为我的用户定义一个角色,该外键引用我的 "roles" table.[=20 的 "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');
        });
    }

Models/User

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]: Integrity constraint violation: 1452 Cannot add or update >a child row: a foreign key constraint fails (projectsms.users, >CONSTRAINT users_role_id_foreign FOREIGN KEY (role_id) REFERENCES >roles (id))

如果您知道我的问题出在哪里,请告诉我!

由于您的结构取决于每次使用都必须有一个角色这一事实,因此您应该在迁移中包括插入默认角色。

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(),
        ]);
    }

[...]

}