【问题标题】:General error: 1215 Cannot add foreign key constraint [ Laravel 5.8 ]一般错误:1215 无法添加外键约束 [Laravel 5.8]
【发布时间】:2019-12-27 19:35:26
【问题描述】:

我想在一个模型中添加两​​个foreign key,但它似乎不起作用并返回这样的错误

SQLSTATE[HY000]:一般错误:1215 无法添加外键约束(SQL:alter table expenses 添加约束expenses_shop_id_foreign 外键(shop_id)引用shopsid))

下面是我的模型

<pre>
    Schema::create('expenses', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('user_id');
        $table->unsignedBigInteger('shop_id');
        $table->date('date');
        $table->string('description');
        $table->double('amount');
        $table->timestamps();

        $table->foreign('user_id')->references('id')->on('users');
        $table->foreign('shop_id')->references('id')->on('shops');
    });
</pre>

我的店铺模型

<pre>
    Schema::create('shops', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->string('description');
        $table->timestamps();
    });
</pre>

有没有办法让它工作?在此先感谢...

【问题讨论】:

  • 您应该在定义foreign key 时使用index()$table-&gt;unsignedBigInteger('user_id')-&gt;index();$table-&gt;unsignedBigInteger('shop_id')-&gt;index();
  • @SalmanZafar 还是不行,兄弟..
  • 您是在刷新数据库还是在新迁移中添加此列?
  • 是的,兄弟我跑php artisan migrate:fresh@SalmanZafar
  • 改用php artisan migrate:refresh

标签: laravel foreign-keys


【解决方案1】:

unsignedBigInteger 将在数据库中创建无符号整数,但 bigIncrements 将创建有符号整数,因此您需要将它们设为相同类型。

要么你改变

商店表:

$table->bigIncrements('id');

费用表:

$table->BigInteger('shop_id');

商店表:

$table->increments('id')

费用表:

$table->unsignedInteger('shop_id');

【讨论】:

  • 抱歉,如果您使用了第一个解决方案,那就错了,也许我的回答不清楚,我会编辑它。使用 $table->BigInteger('shop_id');如果商店表已迁移
  • $table->bigInteger('shop_id'); // 小写 b
猜你喜欢
  • 2019-08-02
  • 2020-06-12
  • 1970-01-01
  • 2019-09-08
  • 2021-03-29
  • 2018-07-29
  • 2018-07-29
  • 1970-01-01
  • 2021-07-03
相关资源
最近更新 更多