laravel Eloquent 查询 - 多列上的 COUNT 和 SUM
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27730806/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Eloquent query - COUNT and SUM on multiple columns
提问by Peter
I am trying to use knowledge from this question question already answered
我正在尝试使用已经回答的这个问题的知识
In my pivot table user_attitudesI have two columns:
在我的数据透视表 user_attitudes 中,我有两列:
importance (the users are declaring their interest (0,3))
attitude (basically this one is for upvoting and downvoting, values are '-1', '0' and '1')
重要性(用户声明他们的兴趣 (0,3))
态度(基本上这个是用于upvoting和downvoting,值为'-1','0'和'1')
What I have now:
我现在所拥有的:
I can print a list of Entity ordered by the value created by selectRaw.
我可以打印由selectRaw创建的值排序的实体列表。
What I need:
我需要的:
I wish to print a different all four values described below, unregardedly which one is used for sorting
我希望打印下面描述的所有四个不同的值,不管哪个用于排序
I wish to create several sorting switches with AJAX, so that users can change sorting.
我想用 AJAX 创建几个排序开关,以便用户可以更改排序。
For every I need to output up to four counts: Total importance score:
对于每个我需要输出最多四个计数:总重要性得分:
SUM(user_attitudes.importance) AS importance
To show how many users are observing the Entity:
要显示有多少用户正在观察实体:
COUNT(user_attitudes.importance) AS observing
Total count of upvotes and downvotes:
赞成票和反对票的总数:
SUM(user_attitudes.attitude) AS karma
Number of users who down- or upvoted a iven Entity:
否决或赞成 iven 实体的用户数量:
COUNT(user_attitudes.importance) AS
How I can expand the below query? Where in this query I can ask for the above extra numbers?
我如何扩展以下查询?在此查询中,我可以在哪里要求上述额外数字?
$rank_entities = Entity::leftJoin('user_attitudes', function($q){
$q->on('entity_id', '=', 'entities.id');
$q->where('item_type', '=', 'entity');
})
->selectRaw('entities.*, SUM(user_attitudes.importance) AS importance')
->groupBy('entities.id')
->orderBy('importance', 'desc')
->take(6)
->get();
I tried to add another
我试图添加另一个
->selectRaw('entities.*, SUM(user_attitudes.attitude) AS karma')
but it seems only one selectRaw can create a printable variable Any ideas? thx.
但似乎只有一个 selectRaw 可以创建一个可打印的变量 有什么想法吗?谢谢。
采纳答案by lukasgeiter
Just add them to the current selectRaw
? Here I'm using an array to make it a bit cleaner:
只需将它们添加到当前selectRaw
?在这里,我使用了一个数组来使它更简洁:
$selects = array(
'entities.*',
'SUM(user_attitudes.importance) AS importance',
'COUNT(user_attitudes.importance) AS observing',
'SUM(user_attitudes.attitude) AS karma'
);
// query ...
->selectRaw(implode(',', $selects))