You may have to use Group by.
Ordering collection by relationship data
Hello,
I'd like to order my collection of Legs on data from their relationship, Concert. I got it set-up as following:
Leg has many Concert (Leg consists of name-field) Concert belongsTo Leg (Concert consists of date-field, amongst others)
I want to sort my Legs on the earliest Concert date. Something like Leg::orderBy('concerts.date');
I've tried a join, but that's not working because I get way too many results (all the concerts). Of course I could group by, but it also turns my results in a set of Concerts, and I want Legs.
Same question, how would I manage this withing a relationship? For instance: a Leg belongs to a Tour. And a Tour hasMany Legs. When I call my $tour->legs, I want this to be sorted by Concert's date.
So:
//LegsController.php
$legs = Leg::orderBy('name', 'asc'); // How to sort on Concert date?
//Tour.php
public function legs() {
return $this->hasMany('App\Models\Leg')->orderBy('name', 'asc');
// How to sort on Concert date?
}
Okay, I got a little step closer to the nature of the problem.
$legs = Leg::all();
$legs->first()->concerts()->get(); // returns list of concerts
$legs->first()->id; // id of leg.. like I want it
$legs = Leg::join('concerts', 'legs.id', '=', 'concerts.leg_id')
->orderBy('concerts.date', 'desc')
->groupBy('legs.name')
->paginate(25);
$legs->first()->concerts()->get(); // returns no concerts
$legs->first()->id; // id of first concert - which explains there's no related concerts
That's because when you join two tables and end up with multiple columns with the same name MySQL returns the latest value.
I fixed this by adding ->select(['legs.*']) to my statement and omitting all concert data. Don't need it anyways.
Thank you all for thinking with me!
Please or to participate in this conversation.