Laravel Eloquent 多重求和
Posted
技术标签:
【中文标题】Laravel Eloquent 多重求和【英文标题】:Laravel Eloquent multiple sums 【发布时间】:2022-01-01 07:33:58 【问题描述】:联系人表的列
Name=client_id
Name=room_id
Name=stats - a number
Name=date
我需要计算一年、每周、每月和每季度的统计数据,以及统计数据列的许多总和。我为旧系统创建了这个 SQL,现在我需要获取 stats 列的总和,而不是像以前那样计算它们。
SELECT
SUM(
date > '2021-01-11 00:00:00'
AND date < '2021-01-18 00:00:00'
AND room_id = 6
AND client_id = 1
) as week1,
SUM(
date > '2021-12-20 00:00:00'
AND date < '2021-12-27 00:00:00'
AND room_id = 6
AND client_id = 1
) as week51,
SUM(
date > '2021-01-01 00:00:00'
AND date < '2021-01-31 23:59:00'
AND room_id = 6
AND client_id = 1
) as month1,
SUM(
date > '2021-12-01 00:00:00'
AND date < '2021-12-31 23:59:00'
AND room_id = 6
AND client_id = 1
) as month12
FROM
contact;
是否可以使用 Eloquent 来实现,或者我需要使用 DB 外观?如果使用 Eloquent 是一种更简单的方法,我想使用它。
【问题讨论】:
您需要按month
或week
对记录进行分组
请提供一些示例数据
【参考方案1】:
你可以这样做
$conditions = [
'week1' => [
['date' , '>' , '2021-01-11 00:00:00' ] ,
['date' , '<' , '2021-01-18 00:00:00' ] ,
['room_id' , 6 ] ,
['client_id' , 1 ] ,
] ,
'month1' => [
['date' , '>' , '2021-12-01 00:00:00' ] ,
['date' , '<' , '2021-01-31 23:59:00' ] ,
['room_id' , 6 ] ,
['client_id' , 1 ] ,
] ,
];
$output = [];
foreach ($conditions as $k=>$condition )
$output[$k] = Contact::where($condition)->sum('stats');
---------------- 使用联合 -----------------
$conditions = [
'week1' => [
['date' , '>' , '2021-01-11 00:00:00' ] ,
['date' , '<' , '2021-01-18 00:00:00' ] ,
['room_id' , 6 ] ,
['client_id' , 1 ] ,
] ,
'month1' => [
['date' , '>' , '2021-12-01 00:00:00' ] ,
['date' , '<' , '2021-01-31 23:59:00' ] ,
['room_id' , 6 ] ,
['client_id' , 1 ] ,
] ,
];
$base_query = false ;
foreach ($conditions as $k=>$condition )
$query = Contact::selectRaw("SUM(stats) as total , '$k' as 'title' ")->where($condition) ;
if($base_query === false )
$base_query = $query ;
else
$base_query->union($query);
$results = $base_query->get() ;
foreach ($results as $result )
dump($result->title , $result->total );
【讨论】:
是什么让你认为他们不是指SUM()
?我认为他们想总结stats
列。
@miken32 是的,我的错,我正在查看查询并没有看到 sum 列...应该有红色的描述
@hretic 是正确的,但是这会运行多个查询,我只想要一个语句。我确实想出了类似 $client->stats->where('room_id', 6)->whereBetween('date', ['2021-11-19', '2021-11-20'])->sum('stats')
的东西,但这需要运行多次。
@AlexandruPopa 所以我想你可以使用union
或某种subquery
如果可能的话......我已经在我的答案中添加了联合解决方案以上是关于Laravel Eloquent 多重求和的主要内容,如果未能解决你的问题,请参考以下文章