在 Laravel eloquent 数据库播种器/工厂中播种关系数据 - 类型错误 - Arg 1 应该是 Eloquent\Model - 给定的集合

Seeding relational data in Laravel eloquent database seeder / factory - Type error - Arg 1 should be Eloquent\Model - Collection given

我正在尝试在 Laravel 5.5 应用程序中使用关系数据为 table 播种。

我有这两个tables/models:

关于app\User.php模型文件;我有以下 hasMany 关系:

public function questions()
{
    return $this->hasMany(Question::class);
}

这是我的 database/factories/QuestionFactory.php

<?php

use Faker\Generator as Faker;

$factory->define(App\Question::class, function (Faker $faker) {
    static $user_id;

    return [
        'user_id' => $user_id,
        'subject' => $faker->sentence(15),
        'body' => $faker->paragraph(3)
    ];
});

和我的database/factories/UserFactory.php

<?php

use Faker\Generator as Faker;

$factory->define(App\User::class, function (Faker $faker) {
    static $password;

    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'password' => $password ?: $password = bcrypt('123456'),
        'remember_token' => str_random(10),
    ];
});

鉴于以上情况;我正在尝试像这样在我的虚拟数据播种机中使用它:

class DummyDataSeeder extends Seeder
{
    public function run()
    {
        // Seed dummy users
        factory(App\User::class, 10)->create()->each(function($user)
        {
            // With dummy questions
            $user->questions()->save(factory(App\Question::class, 3)->make());
        });
    }
}

The goal was to create 10 dummy users, and for each users to have 3 questions each.

当我使用上述设置为数据库播种时;我收到以下错误:

[Symfony\Component\Debug\Exception\FatalThrowableError] Type error: Argument 1 passed to Illuminate\Database\Eloquent\Relations\HasOneOrMany::save() must be an instance of Illuminate\Database\Eloquent\Model, instance of Illuminate\Database\Eloquent\Collection given, called in C:\xampp\htdocs\myapp.local\database\seeds\DummyDataSeeder.php on line 18

这样试试:

factory(App\User::class, 10)->create()->each(function ($u) {
  $u->questions()->saveMany(factory(App\Question::class, 3)->make());            
});

在 laravel 中的工厂中生成关系数据的最佳方式。

<?php

use Faker\Generator as Faker;

$factory->define(App\Order::class, function (Faker $faker) {
    return [
        'product_id' => App\Product::all()->random()->id,
        'user_id' =>  App\User::all()->random()->id,
        'price' => $faker->randomNumber(6),
        'qty' => $faker->randomDigit(1),
    ];
});