Laravel 在单个子句中使用多个 where 和 sum
问题描述
在我的数据库中,我有 instagram_actions_histories
表,其中有 action_type
列,在该列中我有不同的数据,例如 1
或2
或 3
in my database i have instagram_actions_histories
table which into that i have action_type
column, in the column i have unlike data such as 1
or 2
or 3
我正在尝试获取关系船中的此表数据并对存储在列中的这些值求和,例如
i'm trying to get this table data in relation ship and summing this values which stored in column, for example
顺便说一句,这段代码是不正确的,因为我想得到所有 history
里面有多个 sum
btw, this code is not correct, in that i want to get all history
with multiple sum
inside that
例如(伪代码):
更新:
错误:
我该如何实施这个解决方案?
how can i implementing this solution?
更新:
InstagramAccount 类:
InstagramActionsHistory 类:
用户类别:
推荐答案
另一种为不同类型的动作获取条件总和的方法,你可以在你的 中定义一个
模型如 hasOne()
关系InstagramAccount
Another approach to get conditional sum for your different types of action, you can define a hasOne()
relation in your InstagramAccount
model like
然后您可以将相关数据预先加载为
Then you can eager load the related data as
采用这种方法将仅执行一个额外的查询,以根据您的条件获得 3 个不同的总和结果
Going through with this approach will execute only one extra query to get 3 different sum results based on your criteria
虽然与使用 withCount
的其他方法(这也是一个有效的答案)相比,将为每个操作类型添加 3 个相关的相关子查询,这可能会导致性能开销,生成的查询将看起来有些东西如下图
While as compare to other approach (which is a valid answer also) using withCount
will add 3 dependent correlated sub queries for each action type which may result as a performance overhead, generated query will look something like below
要检查生成的查询,请参阅Laravel 5.3 - 如何记录页面上的所有查询?
To check the generated queries refer to Laravel 5.3 - How to log all queries on a page?
这篇关于Laravel 在单个子句中使用多个 where 和 sum的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!