如何将非重复计数SQL查询转换为Laravel口才查询

时间:2019-03-14 21:22:51

标签: sql laravel eloquent

我想将此SQL查询转换为laravel雄辩的查询。这样我就可以创建

SELECT
    count(distinct article_id) as assigned
FROM
    actions
WHERE
    action_id = 1 and
    set_id = 1

我可以将查询转换为有效的原始请求

DB::table('actions')->select(DB::raw('count(DISTINCT article_id) as assigned'))
        ->where('action_id', 1)
        ->where('set_id', 1)
        ->get();

但是我想弄清楚如何做

$sets = Set::withCount(['actions as assigned' => function ($q) {
    $q->distinct()
        ->select('article_id')
        ->where('action_id', '=', 1);
}])->get();

或这个

$sets = Set::withCount(['actions as assigned' => function ($q) {
    $q->distinct('article_id')
        ->where('action_id', '=', 1);
}])->get();

最终我想让我的Set模型包含这样的作用域方法

public function scopeWithAssignedCount($query){
    $query->withCount(['actions as assigned' => function ($q) {
        $q->distinct('article_id')
            ->where('action_id', '=', 1);
    }])
}

因此我可以在控制器中的单个呼叫中添加多个计数

$sets = Set::withAssignedCount()
    ->withUnassignedCount()
    ->where('palm' => $face)
    ->get();

按评论编辑


我想使用以下类似的记录来进行记录。

public function scopeWithAssignedCount($query)
{
    $query->withCount(['actions as assigned' => function ($q) {
        $q->where('action_id', 1);
    }]);
}

1 个答案:

答案 0 :(得分:1)

检查此查询

$count = Set::select('article_id as assigned');
if(!empty($action_id)){
   $count = $count->where('action_id', $action_id); 
}
if(!empty($set_id)){
   $count = $count->where('set_id', $set_id); 
}
$count = $count->distinct('article_id')->count('article_id');