A
A
Alexander Gamov2019-06-26 13:25:34
Laravel
Alexander Gamov, 2019-06-26 13:25:34

Why is the custom attribute not loading?

There is a Clinic with many Doctors. The Doctor has a custom property "custom_atr" that I want to add to the output (I know what can be written in the model class protected $appends = ['custom_atr'];, but this will always be distributed.)
Here is the code.

$clinic = $clinic->find(1);
$clinic->load([
    'doctors' => function ($q) {
        $q->each(function ($doctor) {
            $doctor->append('custom_atr');
        });
    }
]);

After serialization, the Doctor does not have this field.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Sokharev, 2019-06-28
@slowdream

The closure passed to the "load" method of the model or to the "with" method of the query builder takes as input Illuminate\Database\Eloquent\Relations\Relation (in this case, maybe HasMany or BelongsToMany). That is, it is the same as if you wrote:

$clinic->doctors()->each(function ($doctor) {
    $doctor->append('custom_atr');
})

Which would not lead to any result, in view of the fact that Eloquent does not have an IdentityMap that would allow you to associate the records pulled out by the each() bypass with the records in the relationship.
Here's what really helps:
$clinic = Clinic::with('doctors')->find(1);
$clinic->doctors->each(function ($doctor) {
    $doctor->append('custom_atr');
});

Here we iterate over the already loaded doctors.
In general, in this particular case, when we are interested in one particular clinic, even `with` is an extra step, because on the next line the doctors will still be lazily loaded. But for clarity, you can leave.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question