John Davidson

php - Laravel eager loading with two Fk to same table

0 comments
Message:


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


My Answer:
To use eager loading in Laravel with two foreign keys to the same table, you can define the relationships in your models and then use the `with()` method when querying the data.

Assuming you have a `Team` model with a `country_id` and `opponent_id` foreign keys referencing the `id` column in the `teams` table, you can define the relationships as follows:

php
class Team extends Model
{
public function country()
{
return $this->belongsTo(Team::class, 'country_id');
}

public function opponent()
{
return $this->belongsTo(Team::class, 'opponent_id');
}
}


Then, when querying the data, you can use eager loading with the `with()` method:

php
$teams = Team::with('country', 'opponent')->get();


This will load the `country` and `opponent` relationships for each team in a single query, improving performance compared to lazy loading.

Rate this post

4 of 5 based on 5364 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us