Laravel eager loading with two Fk to same table

Viewed 220

I want use Eager loading in Laravel 8 with a relations of two foreign keys to the same table.

Teams table

id name
120 Germany
245 Italy

Fixtures table

id timestamp home_id away_id winner_id home_goals away_goals
1 1607803200 120 245 120 2 0

Fixture Model

public function home()
{
    return $this->belongsTo(Team::class, "home_id");
}

public function away()
{
    return $this->belongsTo(Team::class, "away_id");
}

public function winner()
{
    return $this->belongsTo(Team::class, "winner_id");
}

In controller, even with $fixtures = Fixture::with(["home", "away", "winner"])->get(); the N+1 Query detector package advise me from that problem.

Are there any way to use eager loading with multiple foreign keys belongs to the same table?? If not, any suggestions to modify the database structure in any better way?

Thank you!

UPDATED: Add the requested info. Seen in the laravel debugbar now, I see only one duplicate query and I think it´s makes sense, are the two relations loaded in with.. So, it´s correct?

Using the data in the view:

@foreach($fixtures as $fixture)
    <div class="flex items-center ">
        <div>
            <img class="object-scale-down h-12 w-12 border border-indigo-600" src="{{ $fixture->home->logo }}" />
        </div>
        <div class="flex-auto ml-5">
            {{ $fixture->home->name }}
        </div>
        <div class="flex-auto">
        </div>
        <div class="flex-auto mr-5 text-right">
            {{ $fixture->away->name }}
        </div>
        <div class="">
            <div>
                <img class="object-scale-down h-12 w-12 border border-indigo-600" src="{{ $fixture->away->logo }}" />
            </div>
        </div>
    </div>
@endforeach

Data from Laravel DebugBar: enter image description here

enter image description here

0 Answers
Related