【问题标题】:Cannot add foreign key constraint, - laravel无法添加外键约束,- laravel
【发布时间】:2019-10-26 15:37:11
【问题描述】:

我遇到了迁移问题。表如下。

public function up()
{
    Schema::create('users_articles_likes', function (Blueprint $table) {
        // $table->increments('id');
        $table->integer('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users');
        $table->integer('article_id')->unsigned();
        $table->foreign('article_id')->references('id')->on('articles');
        $table->primary(['user_id', 'article_id']);
        $table->timestamps();
    });
}

当我尝试迁移它时。它不会推动整个桌子。只需推送user_idarticle_id

这是我在终端中显示的错误。

SQLSTATE[HY000]:一般错误:1215 无法添加外键约束 (SQL:alter tableusers_articles_likes添加约束 users_articles_likes_user_id_foreign 外键 (user_id) 参考users (id))

用户

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

【问题讨论】:

  • 你能分享你的users表迁移吗?
  • 我编辑问题。用用户表更新它。 @纳科夫
  • 看看下面我的回答:) 希望对你有帮助。

标签: laravel


【解决方案1】:

所以问题是因为错误的数据类型。在你的用户表中你有bigIncrements这是Big Integer数据类型,在另一个表中integer

所以试试这个:

$table->bigInteger('user_id')->unsigned();
// or
$table->unsignedBigInteger('user_id');

请务必检查article_id

【讨论】:

  • 哦,谢谢你的指出。这对我来说是一个很好的做法。需要等待检查10分钟。
  • @parabellum 请不要忘记标记它:) 谢谢。
猜你喜欢
  • 2020-09-12
  • 1970-01-01
  • 2021-10-27
  • 2018-11-25
  • 2016-11-11
  • 2017-09-06
  • 2017-03-03
  • 1970-01-01
  • 2022-11-17
相关资源
最近更新 更多