Home > Net >  Laravel order by function for 3-level relation
Laravel order by function for 3-level relation

Time:03-04

I have this function for ordening a column in a 2-level relation.

public function sortByRegionUp(Request $request)
    {
        $hotels = Hotel::with('region')
            ->orderBy(Region::select('name')
            ->whereColumn('id', 'hotels.region_id'), 'asc')
            ->paginate(10);

        return view('hotel.index', compact('hotels'));
    }

How do i convert this code for use in a 3-level relation (hasManyTrough)? I want to order hotels by country->name.

Hotel

  • id
  • region_id
  • name
  • ...

Region

  • id
  • country_id
  • name
  • ...

Country

  • id
  • name
  • ...

CodePudding user response:

 public function sortByRegionUp(Request $request)
{
    $hotels = Hotel::with('region')
         ->withCount(['region as region_name_for_order_by' => function($query) {
             $query->select('name');
         }])->orderBy('region_name_for_order_by', 'ASC')->paginate(10);

    return view('hotel.index', compact('hotels'));
}

CodePudding user response:

Add belongsTo relation in Region Model

public function country(){
    return $this->belongsTo(Country::class, 'country_id');
}

  public function sortByRegionUp(Request $request)
{
    $hotels = Hotel::with('region')
        ->withCount(['region.contry as contry_name_for_order_by' => function($query) {
            $query->select('name');
        }])->orderBy('contry_name_for_order_by', 'ASC')->paginate(10);

    return view('hotel.index', compact('hotels'));
}
  • Related