无法迁移:-seed errno:150“外键约束格式不正确”

时间:2020-08-26 01:15:47

标签: laravel

在这里,我和另一个errno 150在一起。现在,这里的大多数事情都没有运气,我需要一个专家,他可能会在我的代码中看到错误。

尝试php artisan migrate:fresh --seed

收到错误1005-150

SQLSTATE[HY000]: General error: 1005 Can't create table `webmall`.`order_items` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `order_items` add constraint `order_items_product_id_foreign` foreign key (`product_id`) references `products` (`id`) on delete cascade)

order_items迁移:

Schema::create('order_items', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('order_id');
            $table->unsignedBigInteger('product_id');

            $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
            $table->foreign('order_id')->references('id')->on('orders')->onDelete('cascade');

            $table->float('price');
            $table->integer('quantity');

            $table->timestamps();
        });

Databaseseeder.php

public function run()
    {
        // $this->call(UserSeeder::class);
        $this->call(ProductSeeder::class);
        $this->call(DataTypesTableSeeder::class);
        $this->call(DataRowsTableSeeder::class);
        $this->call(CategoriesTableSeeder::class);
        $this->call(PostsTableSeeder::class);
        $this->call(PagesTableSeeder::class);
        $this->call(MenusTableSeeder::class);
        $this->call(MenuItemsTableSeeder::class);
        $this->call(RolesTableSeeder::class);
        $this->call(UserRolesTableSeeder::class);
        $this->call(PermissionsTableSeeder::class);
        $this->call(PermissionRoleTableSeeder::class);
        $this->call(SettingsTableSeeder::class);

        $this->call(UsersTableSeeder::class);

像往常一样谢谢你!

1 个答案:

答案 0 :(得分:0)

这是因为您的外键与它引用的主键的类型不同。

使用bigIncrements作为id /主键列是很常规的,因此,如果要引用它,则必须使用bigInteger 因此您的迁移应该像

Schema::create('order_items', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('order_id');
        $table->BigInteger('product_id');

        $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
        $table->foreign('order_id')->references('id')->on('orders')->onDelete('cascade');

        $table->float('price');
        $table->integer('quantity');

        $table->timestamps();
    });