假设我有 4 个表要迁移,它们在我的程序中按这些顺序列出。
2019_11_11_021524_create_device_brands_table.php 2019_11_11_021820_create_device_types_table.php 2019_11_11_025212_create_transactions_ins_table.php 2019_11_11_150443_create_device_statuses_table.php
然后我在 transactions_ins
public function up()
{
Schema::create('transactions_ins', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('DeviceType_id')->nullable();
$table->unsignedBigInteger('DeviceBrand_id')->nullable();
$table->unsignedBigInteger('DeviceStatus_id')->nullable();
$table->timestamps();
//Foreign Key
$table->foreign('DeviceType_id')->references('id')->on('device_types');
$table->foreign('DeviceBrand_id')->references('id')->on('device_brands');
$table->foreign('DeviceStatus_id')->references('id')->on('device_statuses');
});
}
当我使用php artisan migrate
迁移表时,出现这个错误
SQLSTATE[HY000]: General error: 1005 Can't create table
inventory
.transactions_ins
(errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter tabletransactions_ins
add constrainttransactions_ins_devicestatus_id_foreign
foreign key (DeviceStatus_id
) referencesdevice_statuses
(id
))
但是当我从 transactions_in
迁移表中删除 DeviceStatus_id
时,错误消失了,我知道它的发生是因为 Laravel 不知道 device_statuses
表不存在,我应该如何解决这个问题,我应该只删除 transactions_in
迁移表吗?
最佳答案
编辑你的迁移文件名 2019_11_11_150443_create_device_statuses_table.php.set a name that create before your transactions_ins_table
2019_11_11_023443_create_device_statuses_table.php
这意味着您的表是在您的 transactions_ins_table 之前创建的。
关于php - 如果在 Laravel 6 中使用外键的表后面列出引用表,则不能在迁移中使用外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58815161/