1#获取别名
Hotel::query()
->where('city_id', $city_id)
->get(['hotel_name as name', 'id as value'])
->toArray();
//或者
Hotel::query()
->where('city_id', $city_id)
->select('hotel_name as name', 'id as value')
->toArray();
2#懒加载
Eloquent使用with懒加载必须通过$eloqumentModel->relationShip 获取到Collection而不是$eloqumentModel->relationShip()获取到hasOne或hasMany
Eloquent使用with的时候,get()获得的结果集是包含relationShip的Collections的,只有通过$eloqumentModel->relationShip才能正确的使用到懒加载机制
//正确写法
$roomTypeBasics = $item->hotel_rooms()
->with(['hotel_room_rate_plans'])
->get()
->filter(function (HotelRoom $xitem) {
return $xitem->hotel_room_rate_plans->where("source", 1)->count() > 0;
})
//...
//错误写法
$roomTypeBasics = $item->hotel_rooms()
->with(['hotel_room_rate_plans'])
->get()
->filter(function (HotelRoom $xitem) {
return $xitem->hotel_room_rate_plans()->where("source", 1)->count() > 0;
})