jeudi 3 août 2017

Laravel Model factories belongsTo relationship not working

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 :)



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire