【发布时间】:2019-12-27 19:35:26
【问题描述】:
我想在一个模型中添加两个foreign key,但它似乎不起作用并返回这样的错误
SQLSTATE[HY000]:一般错误:1215 无法添加外键约束(SQL:alter table
expenses添加约束expenses_shop_id_foreign外键(shop_id)引用shops(id))
下面是我的模型
<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->unsignedBigInteger('user_id')->index();$table->unsignedBigInteger('shop_id')->index(); -
@SalmanZafar 还是不行,兄弟..
-
您是在刷新数据库还是在新迁移中添加此列?
-
是的,兄弟我跑
php artisan migrate:fresh@SalmanZafar -
改用
php artisan migrate:refresh
标签: laravel foreign-keys