如何根据 octobercms 中其他列中的公共值(id)获取列的 SUM
How to get the SUM of a column based on the common value(id) in other column in octobercms
我卡在这里了。希望有人能帮忙。我有一个数据库,用于存储任何项目的购买完成用户。
这是我的 table 在 twig
<tbody>
{% for paid_log in paid_logs %}
{% paid_log.user_id == user.id and paid_log.status == 2 %}
<tr>
<td>{{paid_log.project.name }}</td>
<td>{{paid_log.amount }}</td>
</tr>
{% endif %}
{% endfor %}
</tbody>
结果
|Project ID| Purchase Amount|
1 |1000
1 |1010
2 |2111
4 |9954
1 |9871
4 |6121
我要循环数据库,在项目ID相同的情况下汇总购买金额?
期待这样的事情:
Project ID |Purchase Total
1 |11881
2 |2111
4 |16075
虽然可能,但 Twig 并不适合进行此类计算。代码变得非常混乱。相反,我建议在定义 paid_logs
.
的 onStart()
中创建数据结构
示例:
function onStart()
{
// ... define $paid_logs and $user
$data = [];
foreach ($paid_logs as $paid_log) {
if ($paid_log->user_id == $user->id && $paid_log->status == 2) {
if (!isset($data[$paid_log->project_id])) {
$data[$paid_log->project->id] = 0;
}
$data[$paid_log->project->id] += $paid_log->amount;
}
}
$this['data'] = $data;
}
然后,在你的 Twig 中你可以简化:
{% for project_id, amount in data %}
{{ project_id }} | {{ amount }}
{% endfor %}
我卡在这里了。希望有人能帮忙。我有一个数据库,用于存储任何项目的购买完成用户。
这是我的 table 在 twig
<tbody>
{% for paid_log in paid_logs %}
{% paid_log.user_id == user.id and paid_log.status == 2 %}
<tr>
<td>{{paid_log.project.name }}</td>
<td>{{paid_log.amount }}</td>
</tr>
{% endif %}
{% endfor %}
</tbody>
结果
|Project ID| Purchase Amount|
1 |1000
1 |1010
2 |2111
4 |9954
1 |9871
4 |6121
我要循环数据库,在项目ID相同的情况下汇总购买金额?
期待这样的事情:
Project ID |Purchase Total
1 |11881
2 |2111
4 |16075
虽然可能,但 Twig 并不适合进行此类计算。代码变得非常混乱。相反,我建议在定义 paid_logs
.
onStart()
中创建数据结构
示例:
function onStart()
{
// ... define $paid_logs and $user
$data = [];
foreach ($paid_logs as $paid_log) {
if ($paid_log->user_id == $user->id && $paid_log->status == 2) {
if (!isset($data[$paid_log->project_id])) {
$data[$paid_log->project->id] = 0;
}
$data[$paid_log->project->id] += $paid_log->amount;
}
}
$this['data'] = $data;
}
然后,在你的 Twig 中你可以简化:
{% for project_id, amount in data %}
{{ project_id }} | {{ amount }}
{% endfor %}