【问题标题】:How to convert Distinct Count SQL query into a Laravel Eloquent query如何将 Distinct Count SQL 查询转换为 Laravel Eloquent 查询
【发布时间】:2019-03-14 21:22:50
【问题描述】:

我想将此 SQL 查询转换为 laravel eloquent 查询。所以我可以创建

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

按 cmets 编辑


我想使用如下所示的不同记录。

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

【问题讨论】:

  • 最后一个查询 (Set::withAssignedCount()->[...]) 应该生成什么 SQL?
  • 同初始查询。我想将 sql 查询与其他人链接起来。
  • 它们完全不同,最后一个查询从 sets 表中选择。
  • 我以前做过这个,没有区别,效果很好。我将编辑我的问题。

标签: sql laravel eloquent


【解决方案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');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-03
    • 1970-01-01
    • 2015-02-24
    • 1970-01-01
    • 1970-01-01
    • 2022-07-29
    • 2019-03-02
    • 1970-01-01
    相关资源
    最近更新 更多