我有这个函数,用于在两级关系中排序列。
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'));
}
如何转换此代码以用于三级关系(hasManyTrough(?我想按国家/地区订购酒店->名称
酒店
- id
- 区域id
- 名称
区域
- id
- country_id
- 名称
国家
- id
- 名称
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'));
}
在区域模型中添加belongsTo关系
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'));
}