[英]Laravel Eloquent Model use select count(column)
I just want to use the following raw DB query with Laravel Eloquent model.我只想对 Laravel Eloquent model 使用以下原始数据库查询。
SELECT
<column_name>,
COUNT(<column_name>) AS `value_occurrence`
FROM
<my_table>
GROUP BY
<column_name>
ORDER BY
`value_occurrence` DESC
LIMIT 1;
Let's say I have a model called TestModel
.假设我有一个名为TestModel
的 model。 I just would like to do something like the following.我只想做如下的事情。
TestModel::select('column_name', 'COUNT(column_name) AS occurrences')
->groupBy('column_name')
->orderBy('occurences')
->limit(10)
->get();
Can you help me please?你能帮我吗? Thanks...谢谢...
I just found out that I can use selectRaw to use Count(column_name) in the code however, if there is any better way of doing it, I would like to see it.我刚刚发现我可以使用 selectRaw 在代码中使用 Count(column_name) 但是,如果有更好的方法,我希望看到它。 Thanks...谢谢...
The answer:答案:
TestModel::selectRaw('column_name, COUNT(column_name) AS occurrences')
->groupBy('column_name')
->orderBy('occurences')
->limit(10)
->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.