【问题标题】:Integrity constraint violation when using a Foreign key for a user role将外键用于用户角色时违反完整性约束
【发布时间】: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,>CONSTRAINT users_role_id_foreign FOREIGN 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 table users`添加约束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


【解决方案1】:

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

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

[...]

}

【讨论】:

    猜你喜欢
    • 2016-04-24
    • 2014-11-09
    • 1970-01-01
    • 2020-01-14
    • 1970-01-01
    • 2023-03-03
    • 2021-12-13
    • 2017-10-01
    相关资源
    最近更新 更多