mardi 20 novembre 2018

how to get objects from relation of relation in laravel

I have 3 model: Tournament,Group,Game

I want to give games from Tournament with 2 relations.

for ex: I want games of Tournament 1 (id=1)

The Tournament has Many groups(5,6,8) and each group have One(36,38) or Many(35,37) games

How to get all games of Tournament with relations and eloquent

some thing like this: $games = Tournament::where('id',1)->groups->games->all();

Tournament Model:

public function groups()
{
    return $this->hasMany(Group::class);
}
+-----+------------+  
| id  |    other   |  
+-----+------------+  
| 1   |   ......   |
| 2   |   ......   |  
+-----+------------+  

Group Model and Database:

public function tournament()
{
    return $this->belongsTo(Tournament::class);
}

public function games()
{
    return $this->hasMany(Game::class);
}
+-----+------------+------------+  
| id  |tournament_id|   other   |  
+-----+------------+------------+  
| 5   |     1      |   ......   |  
| 6   |     1      |   ......   |  
| 7   |     2      |   ......   |  
| 8   |     1      |   ......   |  
+-----+------------+------------+  

Game Model & Database:

public function group()
{
    return $this->belongsTo(Group::class);
}

+-----+------------+------------+  
| id  | group_id   |    other   |  
+-----+------------+------------+  
| 35  |     5      |   ......   |  
| 36  |     6      |   ......   |  
| 37  |     5      |   ......   |  
| 38  |     8      |   ......   |  
+-----+------------+------------+  



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire