如何对特定人(id)的元素求和 - laravel
P粉450079266
P粉450079266 2023-09-04 16:39:02
[PHP讨论组]
<p>您好,我如何对特定人员(id)的表列进行求和。例如,我有一个像这样的表(这是表 ProjectHistory 表): </p> <p>我想在我的 colabs 视图中显示特定协作者的所有总和,例如查看下图。(这是协作者表)</p> <p>所以,如果你看一下图片,我就会看到“David”合作的 id 2。所以我想在“Suma”列中输出 ID 为 2 的 colab 的 ProjectHistory 表的总和,因此 ( 3 + 500 = 503 )。我想为所有合作做到这一点。例如,对于 colab_id 3,我想在“Colaboratori”视图中显示(对于 id 3 表示 Valentin)2500+1800 = 4300。我该怎么做?请给我一个想法</p>
P粉450079266
P粉450079266

全部回复(1)
P粉790187507

You can use the sum in the QueryBuilder.

像这样:

$data = ProjectHistory::where('id', 1)->sum('suma');

In your case, you may also use the withSum to obtain the result you want. Like so:

$data = Collaborator::withSum('ProjectHistory', 'suma')->get();

This resulting Collaborator will have an extra key now named: projecthistory_sum_suma which will have the sum of all the suma belonging to that Collaborator.

This of course assumes that you have a hasMany relation with the ProjectHistory model.

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号