首页 > 解决方案 > 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 之后。如果有的话,这会隐藏租金。

任何想法?

此致

标签: sqllaraveleloquent

解决方案


最后这个查询对我有用:

      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();

推荐阅读