生成具有关联关系的种子数据

时间:2018-09-19 05:01:52

标签: php laravel laravel-5.6

我想为一些书生成种子数据,每本书对每个用户都有一个评分。当我为工厂和播种机运行db:seed时,我没有得到理想的结果

图书工厂

use App\Book;
use App\Rating;
use Faker\Generator as Faker;

$factory->define(Book::class, function (Faker $faker) {
return [
    'title'     => $faker->sentence,
    'author'    => $faker->name,
    'user_id'   => 1
];
});

$factory->define(Rating::class, function (Faker $faker) {
return [
    'user_id'   => 1,
    'book_id'   => mt_rand(1, 5),
    'rating'   => mt_rand(1, 5)
];
});

BooksTableSeeder

public function run()
{
    // First remove existing books records
    Book::truncate();

    factory(App\Book::class, 5)->create()->each(function ($book) {
        // Add book rating
        $ratings = factory(App\Rating::class, 1)->make();
        $book->ratings()->saveMany($ratings);
    });
}

错误的行为:此代码返回一本来自一个用户的具有多个评分的书

正确的行为:一本书对每位用户的评价应该只有一个

如何纠正我的代码以实现此目标?

1 个答案:

答案 0 :(得分:1)

尝试在生成评分时设置book_id:

    factory(App\Book::class, 5)->create()->each(function ($book) {
    // Add book rating
    $ratings = factory(App\Rating::class, 1)->create(['book_id' => $book->id]);
    $book->ratings()->saveMany($ratings);
});