Laravel eloquent 多个 belongsTo 播种

Laravel eloquent multiple belongsTo seeding

我有三个模型,UserCategoryArticle

Article 属于 UserCategory,其中外键 user_idcategory_idnot null

我迷路了,试图通过工厂相应地用假数据为数据库播种,这是播种代码...

// 2 categories and 12 articles, 6 per category
// TODO: A user should have 6 articles with mixed categories 
// 3 from each category
// So we will have 2 users
factory(Category::class, 2)->create()->each(function($category) {
    factory(User::class)->create()->each(function($user) use ($category) {
        // How to assign an Article to $category or $user while creating?
        $user->articles()->createMany(
                    factory(Article::class, 3)->make()->toArray()
                ); // category_id can't be null
        // OR
        $category->articles()->createMany(
                    factory(Article::class, 3)->make()->toArray()
                ); // user_id can't be null
    });
});

我会得到两个错误之一

Column user_id doesn't have a default value

Column category_id doesn't have a default value

由于 Article table 迁移

这是合乎逻辑的
$table->increments('id');
$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->unsignedInteger('category_id');
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');

如何将 category_iduser_id 传递给工厂调用?
有没有更好的方法来实现这个目标?

提前致谢

分别为类别播种。

然后为用户播种,并在其中为文章播种。 文章工厂文件中ArticleFactory:

$factory->define(App\Article::class, function (Faker $faker) {

    return [
        'category_id' => App\Category::inRandomOrder()->value('id'),
        ....
        'created_at' => time(),
        'updated_at' => time(),
    ];
});

这可能对您有所帮助

第一个

当你从工厂制作新文章时让用户创建

$factory->define(App\Article::class, function ($faker) use ($factory)  {
    return [
        'user_id' => $factory->create(App\User::class)->id,
        'title' => $faker->sentence,
        'body' => $faker->paragraph
    ];
});

第二

来自你的播种机 在这个例子中,我将创建 3 个类别 * 6 篇文章

factory('App\Category', 3)->create()->each(function($u) {
    $u->posts()->save(factory('App\Article', 6)->create());
});

您可以通过将具有所需属性的数组传递给 make() 方法来覆盖工厂的属性:

改变

$user->articles()->createMany(
  factory(Article::class, 3)->make()->toArray()
);

$user->articles()->createMany(
  factory(Article::class, 3)->make([
    'category_id' => $category->id
  ])->toArray()
);

覆盖 category_id 属性。

https://laravel.com/docs/6.x/database-testing#using-factories