Dear all i was wondering how can i order this collection of data through a relationship
i have a model called Customer where customer can have many reservations
i get my collection like this
Customer::where('tid' , $tid)
->with(['reservations'])
->paginate(20)
while reservations is relation in Customer model and it is hasMany
my question what if i have a filter with two options
- order by maximum reservations
- order by minimum reservations
How i can order those customers by their interactions according to those reservations
i can attach a filter to the query like this
->when($request->get('reservation_filter') != null , function($q) use($request){
if($request->get('reservation_filter') == 'order by maximum reservations'){
// my query here
}else{
// my query here
}
})
CodePudding user response:
Just change order of results based on filter:
$sortingOrder = ('order by maximum reservations' == $request->get('reservation_filter'))
? 'desc'
: 'asc';
Customer::where('tid', $tid)
->withCount('reservations')
->orderBy('reservations_count', $sortingOrder)
->paginate(20);