为了账号安全,请及时绑定邮箱和手机立即绑定

我在 laravel 中创建外键时遇到错误

我在 laravel 中创建外键时遇到错误

PHP
繁华开满天机 2023-09-22 14:45:50
我创建了三个表:产品、类别和子类别。为了在它们之间创建关系,我使用了外键。我该如何解决?sub_categories - 表    Schema::create('sub_categories', function (Blueprint $table) {                $table->string('id');                $table->string('cat_id');                $table->timestamps();                    $table->string('cat_id')                ->references('id')                ->on('categories')                ->onDelete('cascade');            });类别 - 表     Schema::create('categories', function (Blueprint $table) {                $table->string('id');                $table->string('cat_name');                $table->string('cat_image_path')->nullable();                $table->string('cat_description')->nullable();                $table->timestamps();            });产品 - 桌子     Schema::create('products', function (Blueprint $table) {                $table->string('id');                $table->string('prod_name');                $table->string('prod_brand')->nullable();                $table->string('cat_id');                $table->string('prod_description')->nullable();                $table->string('prod_item_code')->nullable();                $table->string('prod_modal')->nullable();                $table->string('prod_size')->nullable();                $table->string('prod_weight')->nullable();                $table->string('prod_height')->nullable();                $table->string('prod_manufacturer')->nullable();                $table->float('prod_price')->nullable();                $table->float('prod_discount')->nullable();                $table->float('prod_quantity')->nullable();                $table->string('prod_image_path')->nullable();                $table->timestamps();                    $table->foreign('cat_id')                ->references('id')                ->on('categories')                ->onDelete('cascade');            });有人可以帮忙解决这个问题吗?
查看完整描述

2 回答

?
宝慕林4294392

TA贡献2021条经验 获得超8个赞

问题是id每个表中的 都是类型string

id必须是 类型unsignedBigInteger。您可以通过编写$table->id()$table->bigIncrements('id');$table->unsignedBigInteger('id')

您的外键字段(例如cat_id等)也不能是类型string。它们必须具有与上面所写相同的类型。

请查看有关此内容的官方文档。我相信这会对你有所帮助。 https://laravel.com/docs/7.x/migrations#foreign-key-constraints


查看完整回答
反对 回复 2023-09-22
?
慕容708150

TA贡献1831条经验 获得超4个赞

创建“sub_categories”表时,您将重复创建“cat_id”字段。我认为您应该在“sub_categories”表中尝试以下操作:


Schema::create('sub_categories', function (Blueprint $table) {

            $table->string('id');

            $table->string('cat_id')

            ->references('id')

            ->on('categories')

            ->onDelete('cascade');

            $table->timestamps();

        });



查看完整回答
反对 回复 2023-09-22
  • 2 回答
  • 0 关注
  • 65 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信