在雄辩的ORM中使用COUNT()函数(Laravel外部) [英] Using COUNT() function in Eloquent ORM (outside Laravel)
问题描述
我正在尝试使用雄辩的ORM复制SQL查询:
I'm trying to replicate an SQL query with Eloquent ORM:
SELECT DISTINCT name, COUNT(name) AS total
FROM tags
WHERE question_id IS NOT NULL
GROUP BY name
ORDER BY name ASC;
这是我在雄辩的ORM中的尝试:
Here is my attempt in Eloquent ORM:
$query = Tag::query();
$query->orderBy('name', 'asc');
->groupBy('name');
->select( array('count(name) as total') );
->whereNotNull('question_id');
但是,这给了我以下错误:
However, this gives me the following error:
SQLSTATE [42S22]:找不到列:1054'字段列表'中的未知列'count(name)'(SQL:SELECT
COUNT(名称)AS
总计FROM
标签位置
标签。
deleted_atIS NULL和
question_idIS NOT NULL GROUP BY
nameORDER BY
名称ASC)
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'count(name)' in 'field list' (SQL: SELECT
COUNT(name)AS
totalFROM
tagsWHERE
tags.
deleted_atIS NULL AND
question_idIS NOT NULL GROUP BY
nameORDER BY
nameASC)
...很明显我没有正确使用它。
... so clearly I'm not using it properly.
我找到了一条帖子,说我应该使用 DB :: raw('COUNT(name)as total')
,但我不知道数据库类在哪里,因为我不在Laravel中工作。如果需要使用它,如何在Laravel之外使用它。我对两者都尝试 use
:
I found a post saying that I should use DB::raw('COUNT(name) as total')
but I don't know where DB class is as I'm not working within Laravel. If I need to use this, how can I use it outside Laravel. I tried use
for both:
use Illuminate\Database\Connection as DB;
use Illuminate\Database\Query\Builder as DB;
...,因为这是使用grep的唯一类,所以我可以找到一个公共场所其中的原始功能。 Query / Builder给我一个错误,Connection运行正常,但是也许我没有正确构建查询对象,因为它给我在MySQL Shell中运行SQL带来的不一致结果。 Kinda陷入困境,有人可以提供任何帮助吗?
..., as these were the only classes, using grep, I could find to have a public 'function raw' within them. Query/Builder gave me an error, and Connection run OK but perhaps I didn't build the query object correctly as it gives me inconsistent results from running SQL in MySQL shell. Kinda hit a dead end, can anyone offer any help?
谢谢
推荐答案
这可行,但不确定是否是最干净的方法: $ query-> selectRaw('DISTINCT name,COUNT(name)as total')
This works, not sure if it's the cleanest way though: $query->selectRaw('DISTINCT name, COUNT(name) as total')
这篇关于在雄辩的ORM中使用COUNT()函数(Laravel外部)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!