我有一个巨大的查询,需要立即修改它并不急于加载withCount,每当我调用propertyimages_count
它总是返回0而不是正确的计数。但是,如果我打电话给$property->propertyimages()->count()
,它会返回正确的数字,但不是急于加载。
我不确定为什么propertyimages_count,我在想也许是别名。
$search = (isset($_GET['sSearch']) ? $_GET['sSearch'] : '');
$get = $this->method_vars($_GET);
$today = date('Y-m-d');
$where = Property::
withCount('propertyimages')
->with(['project', 'latestmaintenance', 'propertyimages'])
->join('projects', 'properties.project_id', '=', 'projects.id')
->where(function( $query ) use ($get) {
if($get['price_from'] >= 1 && $get['price_to'] <= 500000) {
$query->whereBetween('rental_price', [$get['price_from'], $get['price_to'] ]);
}
$query = $get['sqm_from'] >= 1 && $get['sqm_to'] <= 1000 ? $query->whereBetween('sqm', [$get['sqm_from'], $get['sqm_to'] ]) : $query;
if( $get['type'] != '' ) {
if( $get['type'] == 'house' ) {
$query->where('projects.type', 'Housing Project');
} else if( $get['type'] == 'condo' ) {
$query->where('projects.type', 'Condo Project');
} else if( $get['type'] == 'any' ) {
$query->whereIn('projects.type', ['Condo Project', 'Housing Project']);
}
}
$query = $get['view'] != '' ? $query->where('view', $get['view']) : $query;
$query = $get['project'] != '' ? $query->where('project_id', $get['project']) : $query;
$query = $get['bedrooms'] != '' ? $query->where('bedrooms', $get['bedrooms']) : $query;
$query = $get['bathrooms'] != '' ? $query->where('bathrooms', $get['bathrooms']) : $query;
$query = $get['property_status'] != '' ? $query->where('status', $get['property_status']) : $query;
if( $get['status'] != '' ) {
if( $get['status'] == 'rented' ) {
$query->whereRaw('CURDATE() >= check_in')->whereRaw('CURDATE() <= check_out');
} elseif( $get['status'] == 'vacant' ) {
$query->where(function($q) {
$q->whereRaw('CURDATE() NOT BETWEEN check_in AND check_out')->orWhereNull('check_in');
});
}
}
})
->orderBy('projects.name')
->orderBy('unit')
->whereRaw("(SELECT check_in
FROM property_rentals
WHERE property_rentals.property_id = properties.id
ORDER BY
CASE
WHEN check_out >= '{$today}' AND check_in <= '{$today}' THEN 0
WHEN check_in > '{$today}' THEN 1
ELSE 2
END
LIMIT 1) as check_in")
->whereRaw("(SELECT check_out
FROM property_rentals
WHERE property_rentals.property_id = properties.id
ORDER BY
CASE
WHEN check_out >= '{$today}' AND check_in <= '{$today}' THEN 0
WHEN check_in > '{$today}' THEN 1
ELSE 2
END
LIMIT 1) as check_out");
答案 0 :(得分:0)
可能会添加计数图像关系,如下所示:
public function imagesCount()
{
return $this->hasMany('App\ProperyImage')
->selectRaw('property_id, count(*) as count)
->groupBy('property_id');
}
...然后将其添加到with子句