当用户单击链接时,我试图通过使用列chatter_discussion
从数据库中获取特定数据,但出现此错误:
SQLSTATE [HY000]:常规错误:1005无法创建表
forums.chatter_discussion
(错误号:150“外键约束是 格式不正确”)(SQL:alter tablechatter_discussion
add 约束chatter_discussion_user_id_foreign
外键 (user_id
)在更新时删除级联上引用users
(id
) 级联)
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');
});
}
答案 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