Saturday, March 4, 2017

Laravel 5.1 - eager loading relationships to the same table executes multiple queries

I've got a model that has 4 relationships to the same table.

public function driver()
{
    return $this->belongsTo( Admin::class );
}

public function rejectedBy()
{
    return $this->belongsTo( Admin::class, 'rejected_by' );
}

public function reconciledBy()
{
    return $this->belongsTo( Admin::class, 'reconciled_by' );
}

public function updatedBy()
{
    return $this->belongsTo( Admin::class, 'updated_by' );
}

When I eager load all 4 relationships, the Laravel debugbar reports 4 queries to the admin table.

The method I use is:

$report = Report::find(1)
           ->with('driver', 'rejectedBy', 'reconciledBy', 'updatedBy')
           ->get();

Is there a way to group them together into only one query?



via Ethan22

Advertisement