Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;

like image 299
PCampello Avatar asked May 31 '26 19:05

PCampello


1 Answers

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

like image 151
Achraf Khouadja Avatar answered Jun 03 '26 09:06

Achraf Khouadja



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!