0

I have two tables bookings,units,categories,shifts

bookings

bookingId unitId date status categoryId, shiftId

I need ordering conditions like below.

$query = $query->orderBy('date','ASC');
$query = $query->orderBy('status','DESC');
$query = $query->orderBy('shiftId','ASC');
$query = $query->orderBy('unit.name', 'DESC');
$query = $query->orderBy('categoryId','ASC');

I have created shifts, categories, units relationship in Booking Model.

public function shift(){
  return $this->hasOne(Shift::class,'shiftId','shiftId');
}
public function unit(){
  return $this->hasOne(ClientUnit::class,'clientUnitId','unitId');
}
public function category(){
  return $this->hasOne(StaffCategory::class,'categoryId','categoryId');
}

But when I tried, the unit name 4th condition of orderBy is not working properly, all other order conditions are on Bookings table and 4th condition is with the relation table.

How can I do it with only relationship. In this projects I am not used any Joins in this project and I will expect a solution without a Join to units table.

Thank You.

Jishad
  • 2,876
  • 8
  • 33
  • 62
  • You can't do it without joins, because you have to fetch related `units` before you order by them - unless you just order by `unitId` instead - since that already exists on your table. – JTinkers Aug 27 '19 at 05:43
  • I cant do it with unitId, because my client need order by name – Jishad Aug 27 '19 at 05:51
  • You can use laravel collection **sortBy** method for multiple sorting. [REF](https://github.com/laravel/ideas/issues/11) – ThataL Aug 27 '19 at 06:14
  • @Jishad Then again, you can't do it without joins or fetching the data first. – JTinkers Aug 27 '19 at 09:36
  • https://stackoverflow.com/questions/25700529/laravel-eloquent-how-to-order-results-of-related-models – Pawan Acharya Sep 01 '19 at 07:03

0 Answers0