我有 Laravel 5.5 项目在移民中,我对此表示赞同
Schema::create('item_gifts', function (Blueprint $table) {
$table->increments('id');
$table->string('item_gift_name');
$table->integer('item_gift_item_id_from')->unsigned();
$table->foreign('item_gift_item_id_from')->references('id')->on('items');
$table->integer('item_gift_item_id_to')->unsigned();
$table->foreign('item_gift_item_id_to')->references('id')->on('items');
$table->integer('item_gift_quantity');
$table->integer('item_gift_min_order');
$table->timestamps();
});
但我总是讨厌这个错误
In Connection.php line 664:
SQLSTATE[HY000]: General error: 1005 Can't create table `lar
avel`.`#sql-2830_22f` (errno: 150 "Foreign key constraint is
incorrectly formed") (SQL: alter table `item_gifts` add con
straint `item_gifts_user_id_foreign` foreign key (`user_id`)
references `items` (`id`))
In Connection.php line 458:
SQLSTATE[HY000]: General error: 1005 Can't create table `lar
avel`.`#sql-2830_22f` (errno: 150 "Foreign key constraint is
incorrectly formed")
我需要的是将item_gifts中的item_gift_item_id_from与项目中的 ID 连接起来我尝试了很多解决方案,但没有任何工作谢谢。。
试试这段代码:
public function up()
{
Schema::create('item_gifts', function($table) {
$table->increments('id');
$table->string('item_gift_name');
$table->integer('item_gift_item_id_from')->unsigned();
$table->integer('item_gift_item_id_to')->unsigned();
$table->integer('item_gift_quantity');
$table->integer('item_gift_min_order');
$table->timestamps();
});
Schema::table('item_gifts', function($table) {
$table->foreign('item_gift_item_id_from')->references('id')->on('items');
$table->foreign('item_gift_item_id_to')->references('id')->on('items');
});
}
您收到此错误,因为您手动创建了项目表,并且 ID 只是其中的整数:
CREATE TABLE items ( id int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
创建新的迁移并使其在item_gists
迁移之前执行:
Schema::create('item_gifts', function (Blueprint $table) {
$table->increments('id');
});