php - 如果在 Laravel 6 中使用外键的表后面列出引用表,则不能在迁移中使用外键

标签 php mysql laravel laravel-6

假设我有 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

中引用所有这 3 个表
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 table transactions_ins add constraint transactions_ins_devicestatus_id_foreign foreign key (DeviceStatus_id) references device_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/

相关文章:

java - 在 Java 中列出 MySQL 枚举

php - 如何在grocerycrud中进行一对多的CRUD?

php - ZF2 中的 Zend\Db 如何控制事务?

php - Laravel (5.3) Eloquent - 关系问题

php - 好友列表数据库的简单设计

php - 在 laravel 中以相同的原始数据显示

php - Laravel/00webhost 错误 404. 在此服务器上找不到请求的 URL

php - 我想要来自 mysql 数据库的列的 Distinct 值和 orderby 另一列

php - JWT 授权 laravel/angularjs 问题

php - 在yii2框架中使用动态模型时如何设置属性标签?