Is there a way to force relationships to load in a particular order in a Lumen/Laravel model?

68 Views Asked by At

I have a Lumen (8) model with a relationship that is dependent on another relationship. I want to be able to do the following,

    public function getThingId(): int
    {
        return $this->thing->id;
    }

    public function thing(): BelongsTo
    {
        return $this->belongsTo(Thing::class);
    }

    public function otherThing(): HasMany
    {
        return $this->hasMany(OtherThing::class, 'another_id')->where('thing_id', '=', $this->getThingId())->where(/* some more criteria */);
    }

This does not work. $this->getThingId() returns null in the otherThings relationship. If I use $this->thing->id everything works. I would prefer, however, to use $this->getThingId().

Is there a way to force Laravel to load the thing relationship prior to the otherThing relationship? (or maybe there is something else going that I'm not picking up on).

1

There are 1 best solutions below

0
Tony On

You can force the eager loading of the thing relationship before accessing getThingId() by using the load method. Here's how you can modify your otherThing relationship to ensure that the thing relationship is loaded:

public function otherThing(): HasMany
{
    $this->load('thing'); // Eager load the 'thing' relationship

    return $this->hasMany(OtherThing::class, 'another_id')->where('thing_id', '=', $this->getThingId())->where(/* some more criteria */);
}