【问题标题】:Using factory with nested relationships in Laravel 8在 Laravel 8 中使用具有嵌套关系的工厂
【发布时间】:2021-03-11 21:28:26
【问题描述】:

我的模型是UserPostCategory

我正在尝试使用工厂来播种所有数据。 第一级(有帖子的用户)可以正常工作

// Create random users
User::factory()
    ->times(10)
    ->hasPosts(10)
    ->hasCategories(1)
    ->create();

但我希望每个帖子都有一个类别。 我试过这样做(基于this article):

User::factory()
    ->times(10)
    ->has(
        PostFactory::times(5)
            ->hasCategories(1)
            ->create()
    )
    ->hasCategories(1)
    ->create();

但是会抛出这个错误:

SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert into `posts` (`description`, `updated_at`, `created_at`) values (odio facilis molestiae, 2020-11-29 21:22:50, 2020-11-29 21:22:50))

更新:添加了简化的迁移

帖子和类别通过many to many链接起来

用户迁移

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        ...
    });
}

发布迁移

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->id();
        $table->text('title');
        $table->bigInteger('user_id')->unsigned();
        $table->timestamps();

        $table->foreign('user_id')
            ->references('id')->on('users')
            ->onDelete('cascade');
    });
}

类别迁移

public function up()
{
    Schema::create('categories', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->timestamps();
    });
}

【问题讨论】:

    标签: laravel eloquent factory laravel-8


    【解决方案1】:

    我可以看到您的帖子迁移吗!将其添加到您的问题中...

    【讨论】:

    • 我已经添加了迁移:D
    猜你喜欢
    • 2016-06-25
    • 2021-03-08
    • 2019-04-01
    • 1970-01-01
    • 2020-12-28
    • 2021-08-17
    • 1970-01-01
    • 1970-01-01
    • 2021-06-29
    相关资源
    最近更新 更多