【问题标题】:laravel 8 foreign keylaravel 8 外键
【发布时间】:2021-05-24 07:48:26
【问题描述】:

我尝试迁移具有外键的表。每次我迁移我的表时,它都会产生一个错误,即:

一般错误:1215 无法添加外键约束

这是我的表迁移:

Schema::create('profile_pictures', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->bigInteger('user_id')->nullable();
    $table->binary('image')->nullable();
    $table->timestamps();

    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});

这是我的模型:

class ProfilePicture extends Model
{
    protected $fillable = [
        'user_id',
        'image'
    ];

    public function user()
    {
        $this->belongsTo(User::class, 'user_id', 'id');
    }
}

这是我的用户表迁移:

Schema::create('users', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('username');
    $table->string('first_name')->nullable();
    $table->string('last_name')->nullable();
    $table->string('email')->unique();
    $table->string('phone')->nullable();
    $table->timestamp('email_verified_at')->nullable();
    $table->string('password');
    $table->rememberToken();
    $table->timestamps();
});

【问题讨论】:

  • 我们还需要查看 users 表的迁移,以检查“id”字段类型
  • 我已经放了用户迁移表
  • 试试$table->unsignedBigInteger('user_id')->nullable();
  • 错误已经消失但user_id为空
  • user_id 为空是什么意思?迁移只是为了创建数据库表,而不是插入数据。

标签: laravel migration laravel-8


【解决方案1】:

根据WL#148,外键列必须有 相同的数据类型 + 相同的长度 + 相同的比例 作为相应的引用列。

我认为你应该使用

$table->unsignedBigInteger('user_id')->nullable(); 

代替

$table->bigInteger('user_id')->nullable();

【讨论】:

    【解决方案2】:

    将 user_id col 从 bigInteger 更新为 UnsignedBigInteger,因为您需要 PK 和 FK 相同的数据类型和长度。

    Schema::create('profile_pictures', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('user_id');
        $table->binary('image')->nullable();
        $table->timestamps();
    
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    });
    

    我会建议遵循约定,将 foreignId() 方法与 constrained() 一起使用

    示例(来自文档):

    Schema::table('posts', function (Blueprint $table) {
        $table->foreignId('user_id')->constrained();
    });
    

    您可以在此处获取更多详细信息:https://laravel.com/docs/8.x/migrations#foreign-key-constraints

    【讨论】:

      猜你喜欢
      • 2021-04-25
      • 1970-01-01
      • 2021-10-25
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 2021-10-02
      • 2021-12-30
      相关资源
      最近更新 更多