Laravel Model factories belongsTo relationship not working

Viewed 2796

everyone i have a question regarding Laravel Model Factories, i have the following factory definition.

$factory->define(Video::class, function (Faker\Generator $faker) {
    return [
        "title"         => $faker->unique()->text,
        "description"   => $faker->text(),
        "created_at"    => $faker->dateTimeThisYear
    ];
});

Basically this model has two belongsTo relationships with the contents and resources tables, and defines as such a content_id and a resource_id column.

So i expect this seeder to create the content, the resource and then attach them to the Video model before creating it.

    factory(Video::class, 50)->create()->each(function($item) {
        /** @var $item Video */
        $item->content()->associate(factory(Content::class)->create());
        $item->resource()->associate(factory(Resource::class)->create());
    });

However this does not work, and i get an error about the content_id foreign key on the videos table. What am i doing wrong here? Any help is greatly appreciated :)

2 Answers

You can also assign the respective content and resource id factory('App\Content')->create(), and laravel automatically assigns the appropriate id for you. Example:

"resource_id" => factory('App\Content')->create(),
Related