PCampello
PCampello

Reputation: 175

Order by for relationship in eloquent

I have a tables:

  1. Analyses, columns(id, name, game_id(FK));
  2. Games, columns(id, name, round_id(FK));
  3. Round, columns(id, round);

I need get all records of Analyses order by (round_id).

I try Analyses::orderBy('round_id')->get(), but not work;

Upvotes: 3

Views: 9098

Answers (2)

Achraf Khouadja
Achraf Khouadja

Reputation: 6279

First of all, you dont have that column in your analyses table

to do the orderby you have to add this to your relation (assuming they are correctly done)

Analyses model

public function games()
{
    return $this->hasMany(Game::class)->orderBy('round_id'); //see? we can add orderBy to the relation
}

Games model

public function rounds()
{
    return $this->hasMany(Round::class); // i dont know if its manytomany for eal, im just trying to explain 
}

Now you can get all the Analyses with the games and round using eagerloading like this

$test = Analyses::with('games.round')->get();

you can chain another orderby for Analyses like this for exemple

$test = Analyses::with('games.round')->orderby('game_id')->get();

in the above exemple , you will have Analyses ordered by game_id and the games inside each Analyse will be orderedby round_id

I hope this is what you want to do

Upvotes: 4

Hamza Dairywala
Hamza Dairywala

Reputation: 482

Set the following relationships in to the respective model as given below

Analyses model

Round Model

public function games()
 {
   return $this->hasMany('Game','game_id','id'); 
 }

Game Model

public function analyses()
 {
   return $this->hasMany('Analyses','round_id','id'); 
 }

Your Query Should be like This

    $round_game_wise_analyses= Round::with(['game'=>function($query){
                                $query->select()
                                ->with(['analyses'=>function($query){
                                          $query->select(); 
                                        }]);
                                }])->orderBy('id','asc')->get();

Upvotes: 0

Related Questions