这是我在运行php artisan migrate
后的错误:
SQLSTATE [HY000]:常规错误:1005无法创建表
laravel
。brands
(错误号:150“外键约束格式不正确”)(SQL:更改表brands
添加约束brands_b_c_id_foreign
外部键(b_c_id
)引用countries
(c_id
))
这是我的模式代码:
public function up()
{
Schema::create('countries', function (Blueprint $table) {
$table->id('c_id');
$table->string('c_name');
});
}
public function down()
{
Schema::dropIfExists('countries');
}
和:
public function up()
{
Schema::create('brands', function (Blueprint $table) {
$table->id('b_id');
$table->string('b_name');
$table->foreignId('b_c_id');
$table->foreign('b_c_id')->references('c_id')->on('countries');
});
}
public function down()
{
Schema::dropIfExists('brands');
}
[我看到了StackOverflow问题,但对我没有用。我的laravel版本是7.6.0。我的PHP版本是7.4.5。我最近开始学习laravel。有人可以帮我吗?
只需更改表的顺序,希望它能解决您的问题
Schema::create('countries', function (Blueprint $table) {
$table->id('c_id');
$table->string('c_name');
});
然后定义或运行
Schema::create('brands', function (Blueprint $table) {
$table->id('b_id');
$table->string('b_name');
$table->foreignId('b_c_id');
$table->foreign('b_c_id')->references('c_id')->on('countries');
});