staudenmeir / eloquent-json-relations

Laravel Eloquent relationships with JSON keys
MIT License
1k stars 63 forks source link

Defining Json Relation in factory definition #111

Closed ren0v closed 8 months ago

ren0v commented 8 months ago

When creating a Factory, we can define belongsTo relattionships within the definition() method of the factory See https://laravel.com/docs/10.x/eloquent-factories#defining-relationships-within-factories

I tried to do the same for belongsToJson relationship but it seems that it doesn't work.

class SessionFactory extends Factory
{
 /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition(): array
    {
        return [
            // ipsum
            "study_id"  => Study::factory(), //  belongsTo relation
            "tag_ids" => Tag::factory(3), // belongsToJson relation
            // lorem
        ];
    }
}

Has someone succeded in making it worked?

staudenmeir commented 8 months ago

Hi @ren0v, The package can't make this shortcut work, but you also only need to add two method calls:

    public function definition(): array
    {
        return [
            // ipsum
            "study_id"  => Study::factory(), //  belongsTo relation
            "tag_ids" => Tag::factory(3)->create()->pluck('id'), // belongsToJson relation
            // lorem                    ^^^^^^^^^^^^^^^^^^^^^^^
        ];
    }
ren0v commented 8 months ago

Thanks @staudenmeir for your quick answer, makes totally sense.

I'm still figuring out how to correctly setup my tests / factories with your package.

For belongsToJson relations (both ways), I can't use native for() method when defining relationships on a factory. I guess, this is not possible with the package. So my current workaround is the following :

    $panelist = Panelist::factory()->create();
    $invitation = Invitation::factory()->create();

    $panelist->invitations()->attach($invitation->id)->save(); 
    $invitation->invitees()->attach($panelist->id)->save(); 

Would you have done it the same way? or do you see other way of doing it? still asking, so that we have a piece of documentation about factory here for future reference ;)

staudenmeir commented 8 months ago

Yes 👍