首页 > 解决方案 > 关于如何检查子表是否具有某些多个值的雄辩或 SQL 方式

问题描述

检查表是否具有基于给定 ID 的值的 Eloquent 或 SQL 方法是什么?

示例客户表:

id   name    created_at
1   test_1   01/01/2019
2   test_2   01/24/2019
3   test_3   01/25/2019

样品采购表:

id   customer_id   status      created_at
1         2        paid        02/01/2019
2         2        paid        02/02/2019
3         2        unpaid      02/03/2019
4         2        cancelled   02/03/2019
5         3        paid        02/03/2019
6         1        paid        02/03/2019

我想要实现的是检查是否有未付款和取消状态的客户

目前我的代码是这样的:

Customers::with('purchases')->get();

但我希望它只从购买表中获得未付款和取消状态的客户

标签: phpsqllaraveleloquent

解决方案


使用 SQL,您需要并且子句中group by customer_id的条件将为您提供您想要的客户:count(distinct status) = 2having

select customer_id
from purchases
where status in ('unpaid', 'cancelled')
group by customer_id
having count(distinct status) = 2

如果您希望客户只有“未付款”和“已取消”状态而没有其他状态:

select customer_id
from purchases
group by customer_id
having 
  count(distinct status) = 2
  and 
  sum(case when status not in ('unpaid', 'cancelled') then 1 else 0 end) = 0

推荐阅读