errno:150外键约束的格式不正确

rkttyhzu  于 2021-06-25  发布在  Mysql
关注(0)|答案(2)|浏览(402)

我有一个laravel5.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")

我需要的是连接物品\u礼物\u物品\u id从物品\u礼物与物品中的id我尝试了许多解决方案,但没有什么是工作感谢。。

vmjh9lq9

vmjh9lq91#

出现此错误是因为您手动创建了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');
});
j9per5c4

j9per5c42#

请尝试以下代码:

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

}

相关问题