sql - Laravel 查询。仅在 Eloquent 中获得总计 > 0
问题描述
我有这个查询:
public static function totalByAgent(int $agentId)
{
return PropertyListing::select(
DB::raw('SUM(property_listing.rental) as rental'),
DB::raw('SUM(property_listing.sale) as sale'),
'property_category.name as category_name',
'property_category.id as category_id'
)->join(
'property_category',
'property_category.id',
'property_listing.category_id'
)->where('agent_id', $agentId)->groupBy('property_category.id')->get();
}
通过此查询,我获得了待售物业的总和,以及按物业类别出租的物业总和。但是,如果某些房产只有待售房产和 0 出租房产,我的租金总和为 0。
我尝试添加:
->having('sale', '>', 0)->get()
在 groupBy 之后。如果有的话,这会隐藏租金。
任何想法?
此致
解决方案
最后这个查询对我有用:
return Property::published()->select(DB::raw('SUM(property.rental) as rental'),
DB::raw('SUM(property.sale) as sale'),
'property_category.name as category_name',
'property_category.id as category_id')
->join('property_category', 'property_category.id', 'property.category_id')
->whereExists(function ($query) use ($agentId){
$query->select('property_listing.agent_id')
->from('property_listing')
->whereRaw('property.id = property_listing.property_id')
->where('property_listing.agent_id', $agentId);
})->published()
->groupBy('property_category.id')->get();
推荐阅读
- azure-data-lake - 如何在不使用 Visual Studio 的情况下在 Microsoft azure 数据分析中引用用户定义的运算符 (UDO)
- excel - 可以从选择中确定数据透视字段的位置吗?
- python - 拆分字符串时出现AttributeError
- mysql - 如何使用 mysqli 加速此查询?
- javascript - 使用构造函数和类 JavaScript
- bash - Bash:Nginx 版本检查剪切
- reactjs - 变换函数组件 -> 类组件
- .net - EF6 与 EF 核心单一数据模型或多个“大型”数据库与 REST 服务一起使用?
- angular - Ionic3 - 无法绑定到“textMask”,因为它不是“离子输入”的已知属性
- javascript - Preload.js 有时会发送关于 blob url 的错误信息