我有一个包含以下关系的数据库:
有projects
- 人们可以购买的东西,也有user_id
,
有backers
- 购买的人,
有orders
- 每个订单都是按Project
购买Backer
(Backer
只能购买一次Project
。这是一笔金额 - 显示Backer
支付购买Project
我需要的是撰写以下查询 - 鉴于$user_id
,$count
和$sum
找到至少投资$count
个项目的所有支持者user_id
等于$user_id
,并且这些项目的购买金额高于$sum
。
Backer::whereHas('projects', function ($q) use ($sum, $userId){
$q->where('user_id', $userId);
}, '>=', $leastProjectCount)->get();
但它并不限制购买的$sum
更新 所以我提出了这个问题:
select * from `backers` \r\n
WHERE id > 0 \r\n
AND (select count(*)\r\n
FROM `projects` \r\n
inner join `orders` on `projects`.`id` = `orders`.`project_id` \r\n
where `backers`.`id` = `orders`.`backer_id` \r\n
and `user_id` = 6 \r\n
and exists (\r\n
select * \r\n
from `tags` \r\n
inner join `project_tag` on `tags`.`id` = `project_tag`.`tag_id` \r\n
where `projects`.`id` = `project_tag`.`project_id` \r\n
and `id` in (27)\r\n
) \r\n
) >= 1 \r\n
AND (select sum(orders.amount)\r\n
FROM `projects` \r\n
inner join `orders` on `projects`.`id` = `orders`.`project_id` \r\n
where `backers`.`id` = `orders`.`backer_id` \r\n
and `user_id` = 6 \r\n
and exists (\r\n
select * \r\n
from `tags` \r\n
inner join `project_tag` on `tags`.`id` = `project_tag`.`tag_id` \r\n
where `projects`.`id` = `project_tag`.`project_id` \r\n
and `id` in (27)\r\n
) \r\n
) >= 12
请注意,子查询几乎相同,只是第一个使用COunt(*)
而第二个使用sum(orders.amount)
。并且还要注意,如果设置了所有参数,则运行此查询,但是如果未设置某些参数,则可以更短。我得到的问题是我没有对这样的查询进行分页。
答案 0 :(得分:0)
试试这个:
Backer::whereHas('projects', function ($q) use ($sum, $userId){
$q->where('user_id', $userId)
->havingRaw('SUM(amount) > ? ', [$sum]);
}, '>=', $leastProjectCount)->get();