首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >拉拉8外键

拉拉8外键
EN

Stack Overflow用户
提问于 2021-02-22 02:49:13
回答 2查看 13.8K关注 0票数 2

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

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

下面是我的表迁移:

代码语言:javascript
复制
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');
});

这是我的模型:

代码语言:javascript
复制
class ProfilePicture extends Model
{
    protected $fillable = [
        'user_id',
        'image'
    ];

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

下面是我的用户表迁移:

代码语言:javascript
复制
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();
});
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-02-22 05:03:13

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

代码语言:javascript
复制
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()方法

样本(来自文件):

代码语言:javascript
复制
Schema::table('posts', function (Blueprint $table) {
    $table->foreignId('user_id')->constrained();
});

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

票数 4
EN

Stack Overflow用户

发布于 2021-02-22 04:09:25

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

我觉得你应该用

代码语言:javascript
复制
$table->unsignedBigInteger('user_id')->nullable(); 

而不是

代码语言:javascript
复制
$table->bigInteger('user_id')->nullable();
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66309431

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档