Mena
Mena

Reputation: 2049

Generating seed data with relationship

I want to generate seed data for some books and each book will have a rating per user. I am not getting the desired result when I run my db:seed for the factory and seeder

Book Factory

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);
    });
}

Wrong behaviour This code returns a book with multiple ratings from one user

Right behaviour A book should only have one rating per user

How can I correct my code to achieve this goal?

Upvotes: 0

Views: 57

Answers (1)

Daniel W
Daniel W

Reputation: 433

Try to set the book_id when generating the ratings:

    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);
});

Upvotes: 1

Related Questions