BobbyP
BobbyP

Reputation: 2245

How to use Laravel factory to create multiple models with 'belongsTo' relationships

I am trying to create a unit test for my application and wish to test that relationships exist. For my scenario, I have a model "Service" which has a "company_id" field for a belongsTo relationship.

I would like to use a factory in my test to create 10 "Services". Each service should have its own unique "Company"

I am getting closer all the time and my latest attempt was this

Here is the relationship in my Service model

    /**
     * Get the company a specified service belongs to
     *
     * @return BelongsTo
     */
    public function company(): BelongsTo
    {
        return $this->belongsTo(Company::class);
    }

And here is the code in my unit test. To physically see what is happening, I am outputting the results to the console.

    Service::factory()
        ->count(10)
        ->create([
            'company_id' => Company::factory()->create(),
        ]);

    print_r((Company::all())->toArray());
    print_r((Service::with(['company'])->get())->toArray());

The results are interesting.

    COMPANY
    Array
    (
        [0] => Array
            (
                [id] => E39069C262B289573BA59BE5DA3DA182
                [name] => Bartoletti, Boehm and Cronin
                [account_number] => 013
                [phone_number] => (864) 363-8603
                [created_at] => 2022-11-22T10:22:12.000000Z
                [updated_at] => 2022-11-22T10:22:12.000000Z
                [deleted_at] => 
            )

    )

    SERVICES
    Array
    (
        [0] => Array
            (
                [id] => 92D9C3EEC3F550BBE627B0C7295E948E
                [name] => Aut debitis quam excepturi dolor.
                [company_id] => E39069C262B289573BA59BE5DA3DA182
                [created_at] => 2022-11-22T10:22:12.000000Z
                [updated_at] => 2022-11-22T10:22:12.000000Z
                [deleted_at] => 
                [company] => 
            )

        [1] => Array
            (
                [id] => B358067875A3AED5F2590321EE7040E3
                [name] => Labore quia quia doloribus fuga adipisci.
                [company_id] => E39069C262B289573BA59BE5DA3DA182
                [created_at] => 2022-11-22T10:22:12.000000Z
                [updated_at] => 2022-11-22T10:22:12.000000Z
                [deleted_at] => 
                [company] => 
            )

        ... repeated 10 times
    )

How can I use a factory to create 10 services, each with their own company?

Upvotes: 0

Views: 1108

Answers (1)

RossTsachev
RossTsachev

Reputation: 921

For belongsTo relationship you can do:

Service::factory()
    ->count(10)
    ->for(Company::factory())
    ->create();

If you need different parent every time:

Service::factory()
    ->count(10)
    ->hasParent(Company::factory())
    ->create();

Upvotes: 1

Related Questions