Laravel迁移(错误号:150“外键约束格式不正确”)

时间:2019-04-20 16:14:47

标签: php html laravel-5

当用户单击链接时,我试图通过使用列chatter_discussion从数据库中获取特定数据,但出现此错误:

  

SQLSTATE [HY000]:常规错误:1005无法创建表   forums.chatter_discussion(错误号:150“外键约束是   格式不正确”)(SQL:alter table chatter_discussion add   约束chatter_discussion_user_id_foreign外键   (user_id)在更新时删除级联上引用usersid)   级联)

Schema::table('chatter_discussion', function (Blueprint $table) {
    $table->foreign('chatter_category_id')->references('id')->on('chatter_categories')
        ->onDelete('cascade')
        ->onUpdate('cascade');
    $table->foreign('user_id')->references('id')->on('users')
        ->onDelete('cascade')
        ->onUpdate('cascade');
});

Schema::table('chatter_post', function (Blueprint $table) {
    $table->foreign('chatter_discussion_id')->references('id')->on('chatter_discussion')
        ->onDelete('cascade')
        ->onUpdate('cascade');
    $table->foreign('user_id')->references('id')->on('users')
        ->onDelete('cascade')
        ->onUpdate('cascade');
    });
}

2 个答案:

答案 0 :(得分:1)

当迁移到新版本的Laravel,该新版本在架构中定义主键时使用bigIncrements而不是increments时,会发生此问题。 另外,在定义外键关系之前,还需要定义外键的类型。

解决方法是定义外键的类型,然后定义外键的关系,例如:

Schema::table('chatter_discussion', function (Blueprint $table) {
// first define the type of the foreign keys in the schema
$table->bigInteger('chatter_category_id')->unsigned(); // the id of the chatter category
$table->bigInteger('user_id')->unsigned(); // the id of the user
/*
or use:
$table->integer('chatter_category_id');
$table->integer('user_id');
if using older versions of laravel, whatever works
*/        
// THEN define foreign key relations
$table->foreign('chatter_category_id')->references('id')->on('chatter_categories')
                    ->onDelete('cascade')
                    ->onUpdate('cascade');
        $table->foreign('user_id')->references('id')->on('users')
                    ->onDelete('cascade')
                    ->onUpdate('cascade');
    });

对其他引用外键的表执行类似操作

注意,在您的示例中,您没有在id表中定义chatter_discussion列,然后在chatter_post中引用了该列。不知道是错过了它还是在先前的迁移中定义了它。

答案 1 :(得分:0)

public function up() {     Schema::create('companies', function (Blueprint $table) {         $table->bigIncrements('id');         $table->string('name');         $table->text('address');         $table->string('tel1');         $table->string('tel2');         $table->integer('owner');         $table->unsignedBigInteger('access_id');         $table->string('depot_number')->default(2);         $table->timestamps();           $table->foreign('access_id')->references('id')->on('accesses')             ->onDelete('cascade');     }); } 

public function up() {     Schema::create('accesses', function (Blueprint $table) {         $table->bigIncrements('id');         $table->string('type');         $table->string('description');         $table->timestamps();     }); } 

在您的数据库/迁移文件夹中,按名称排序。然后确保 create_accesses_table create_companies_table 之前 enter image description here