错误:150外键约束不正确

时间:2018-01-10 13:14:04

标签: php mysql laravel migration migrate

我有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相关联 我尝试了很多解决方案但没有任何工作 谢谢..

2 个答案:

答案 0 :(得分:2)

试试这段代码:

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'); 
 });

}

答案 1 :(得分:1)

您收到此错误,因为您手动创建了items表,而ID只是其中的整数:

item_gists

创建新迁移并使其在Schema::create('item_gifts', function (Blueprint $table) { $table->increments('id'); }); 之前执行:

{{1}}