Laravel-如何对模型之间的关系求和(即不在记录级别上进行记录)

时间:2019-06-04 11:57:41

标签: php mysql laravel eloquent

性能优化

出于性能原因,我不想用雄辩的语言来产生一个集合。我宁愿让SQL承担繁重的工作,并计算所有符合特定条件的索赔中签署的授权书总数,以避免在每个索赔记录中循环生成PHP(例如,通过withCount等)

我想做些简单的事情:

Claim::join('powers_of_attorney', 'powers_of_attorney.claim_id', '=', 'claims.id')->selectRaw(['claims.id', 'count(case when powers_of_attorney.status = "closed" and powers_of_attorney.claim_id = claims.id and powers_of_attorney.deleted_at is null then powers_of_attorney.id end) as poasSigned'])->sum('poasSigned');

应根据以下条件工作: Laravel Query Builder - Use sum method on a generated attribute

但是我收到错误消息

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'poasSigned' in 'field list' (SQL: select sum(`poasSigned`) as aggregate from `claims` inner join `powers_of_attorney` on `powers_of_attorney`.`claim_id` = `claims`.`id` where `claims`.`deleted_at` is null)

关于如何解决的想法?

索赔模型

id
name
...

授权书模型

id
claim_id
status
...

0 个答案:

没有答案