Jazerix
Jazerix

Reputation: 4801

Laravel relationship implicit caching

I'm a little perplexed about the issue I'm having.

As part of my integration test, I'm testing the relationship between two models.

public function an_applications_status_is_over_deadline()
{
    //Part 1
    $statusId = factory(ApplicationFlowStatus::class)->create([        // id: 1
        'deadline_hours' => 72
    ])->id;
    $application = factory(Application::class)->create([               // id: 1
        'current_status_id' => $statusId
    ]);
    dump([$application->current_status_id, $application->status()->first()->id, $application->status->id]);

    //Part 2
    $newStatus = factory(ApplicationFlowStatus::class)->create([       // id: 2
        'deadline_hours' => 8
    ]);
    $application->current_status_id = $newStatus->id;
    $application->save();
    dump([$application->current_status_id, $application->status()->first()->id, $application->status->id]);
}

On my Application model:

public function status()
{
    return $this->belongsTo(ApplicationFlowStatus::class, 'current_status_id');
}

The first part works flawlessly, however once the send part has executed, the ids gets mixed up and I'm uncertain why.

Dump 1:
array:3 [
    0 => 1
    1 => 1
    2 => 1
]

Dump 2:
array:3 [
    0 => 2
    1 => 2
    2 => 1
]

Why is the second dump still pointing to first status when $application->status->id is used?

I'm wondering is Laravel is caching the relationship behind the scenes :)

Upvotes: 1

Views: 59

Answers (1)

Zoe Edwards
Zoe Edwards

Reputation: 13687

Yes, but it should handle this situation.

You can use $application->refresh() to hopefully solve the problem.

Upvotes: 2

Related Questions