【问题标题】:Solve laravel migration problem with foreign keys用外键解决 laravel 迁移问题
【发布时间】:2020-08-01 19:23:20
【问题描述】:

我编写了迁移并且它们运行良好,直到我尝试制作它们 on delete cascade 我添加了$table->engine = 'InnoDB',没关系。 但是在播种机中,当我尝试运行它们时出现错误

 PDOException::("SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`mohajerat`.`comments`, CONSTRAINT `comments_comment_id_foreign` FOREIGN KEY (`comment_id`) REFERENCES `comments` (`id`) ON
 DELETE CASCADE)")

我知道 stackoverflow 中有一些问题,但没有一个对我有帮助。所以我在这里问任何人都可以提供帮助 这是我的迁移:

  Schema::create('comments', function (Blueprint $table) {
            $table->id();
            $table->engine = 'InnoDB';
            $table->morphs('commentable');
            $table->string('body', 250);
            $table->foreignId('user_id')->constrained('users')->onDelete('cascade');
            $table->foreignId('comment_id')->constrained('comments')->onDelete('cascade');
            $table->timestamps();
        });

这是我的播种机:

    Schema::disableForeignKeyConstraints();
        Comment::truncate();
        Schema::enableForeignKeyConstraints();
        $users = \App\Models\User::all()->toArray();
        foreach ($users as $key => $user) {
//            $comment = \App\Models\Comment::all()->random();
            $post = \App\Models\Article::all()->random();
//            dd($user, $post);
            factory(Comment::class)->create([
                'user_id' => $user['id'],
                'commentable_id' => $post->id,
                'commentable_type' => get_class($post),
                'comment_id' => 0
            ]);
        }

如果你知道,请告诉我。 谢谢!

【问题讨论】:

  • 外键引用的列声明在哪里?您已创建外键但尚未将其分配给任何列

标签: mysql sql laravel migration


【解决方案1】:

注意:您的外键表必须在分配之前创建。检查图像和代码。

在我的产品表中,我添加了“product_categories”和“product_brands”作为参考表。在创建“products”表之前,我已经创建了“products_categories”和“product_brands”迁移。

带有外键的产品表

    Schema::create('products', function (Blueprint $table) {
        $table->id();
        $table->string('title')->unique();
        $table->string('slug')->unique();
        $table->unsignedBigInteger('category_id');
        $table->unsignedBigInteger('brand_id');
        $table->string('image');
        $table->text('description');
        $table->text('information')->nullable();
        $table->integer('stock');
        $table->bigInteger('price');
        $table->bigInteger('sale_price')->nullable();
        $table->string('sku')->nullable();
        $table->timestamps();
        $table->foreign('category_id')->references('id')->on('product_categories')->onDelete('cascade');
        $table->foreign('brand_id')->references('id')->on('product_brands')->onDelete('cascade');
    });

【讨论】:

    猜你喜欢
    • 2014-08-09
    • 2014-03-11
    • 1970-01-01
    • 2013-08-27
    • 2015-01-13
    • 2013-05-31
    • 2015-03-31
    • 1970-01-01
    • 2020-06-05
    相关资源
    最近更新 更多