Laravel查询获取非重复值的出现次数


Laravel query get occurrences of distinct values

编辑:通过在查询中添加 where 子句来解决

    ->where('first.test_id',$test_id)
    ->where('second.test_id',$test_id)
    ->where('first.is_private',0)
    ->where('second.is_private',0)

我有一个包含几列的表格 - id、文本、test_id、is_private 和更多列。

我想选择表格中的所有行,此外,我希望每个对象都包含一个计数器,以便我知道该文本在表格中出现的次数

试图关注这篇文章:http://www.tagwith.com/question_164722_count-occurrences-of-distinct-values-using-laravel-query-builder

但是,我不想对我的结果进行分组,并且还根据测试 id 使用 where 子句

因此,例如,对于以下条目,我想选择test_id=700的条目:

id text test_id
1  abc  700
2  abc  700
3  aaa  700
4  abc  701

输出应如下所示:

$rows[0] = {id = 1, text='abc',count=2}
$rows[1] = {id = 2, text='abc',count=2}
$rows[2] = {id = 3, text='aaa',count=1}

使用以下查询:

    return DB::table('comments AS first')
            ->select(['first.*',DB::raw('count(first.text)')])
            ->join('comments as second','first.text','=','second.text')
            ->where('first.test_id',$test_id)
            ->where('first.is_private',0)
            ->orderBy('first.question_number', 'asc')
            ->orderBy('first.subquestion_number', 'asc')
            ->groupBy('first.id')
            ->get();

我没有得到正确的结果,看起来计数发生在 where 子句之前,所以我在计数中获得的数字是"文本"出现在我的整个表中的数字。

这有点复杂,但要做到这一点,您需要在文本列上联接表本身,按 id 分组,然后选择 count。

这样的事情应该有效...

    $results = DB::table('test as a')
    ->select(['a.id', 'a.text', DB::raw('count(*)')])
    ->join('test as b', 'a.text', '=', 'b.text')
    ->groupBy('a.id')
    ->get();

或原始 SQL

SELECT 
    a.id,
    a.text, 
    COUNT(*)
FROM test A
INNER JOIN test B ON a.text = b.text
GROUP BY a.id;