laraveleloquenteager-loadingeloquent-relationshiplaravel-relations

How to eager load polymorphic relation - In LARAVEL?


In my Device.php Model, I have 2 relations for both antennas and fixed readers.

/**
 * Get All Antennas directly associated with Device
 *
 * @return \Illuminate\Database\Eloquent\Relations\MorphMany
 */
public function antennas() : MorphMany
{
    return $this->morphMany(Antenna::class, 'attachable');
}

/**
 * Get All Fixed Readers of Device
 *
 * @return \Illuminate\Database\Eloquent\Relations\HasMany
 */
public function fixedReaders() : HasMany
{
    return $this->hasMany(FixedReader::class);
}

in My FixedReader.php Model, I've one relation that is with antennas.

/**
 * Get All Antennas of readers
 *
 * @return \Illuminate\Database\Eloquent\Relations\MorphMany
 */
public function antennas() : MorphMany
{
    return $this->morphMany(Antenna::class, 'attachable');
}

in My Antenna.php Model, I can get either Device or Fixed Reader.

/**
 * Get the parent attachable model (Device or Fixed Reader).
 */
public function attachable(): MorphTo
{
    return $this->morphTo();
}

I want to eager load relation when quering on Device Model:

Device::select('devices.*')
                ->with([
                    'fixedReaders' => [
                        'antennas'
                    ],
                    'antennas',
                ])
                ->get();

I tried above but not working.


Solution

  • Use .(dot) to get deeper relationship, try:

    Device::select('devices.*')
        ->with(['fixedReaders.antennas', 'antennas'])
        ->get();