在Laravel eloquent数据库播种机/工厂播种关系数据 - 类型错误 - Arg 1应为Eloquent \ Model - Collection

时间:2017-10-23 09:56:37

标签: php laravel laravel-5 laravel-eloquent laravel-seeding

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

我有这两个表/模型:

  • 用户
  • 问题

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

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

这里是我的数据库/工厂/ 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)
    ];
});

和我的数据库/ 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());
        });
    }
}
  

目标是创建10个虚拟用户,并为每个用户分别提出3个问题。

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

  

[Symfony \ Component \ Debug \ Exception \ FatalThrowableError]输入错误:   争论1传递给   Illuminate \ Database \ Eloquent \ Relations \ HasOneOrMany :: save()必须是   Illuminate \ Database \ Eloquent \ Model的实例,实例   给出了Illuminate \ Database \ Eloquent \ Collection,调用   在线:C:\ xampp \ htdocs \ myapp.local \ database \ seeds \ DummyDataSeeder.php   18

2 个答案:

答案 0 :(得分:5)

试试这样:

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

答案 1 :(得分:0)

在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),
    ];
});