php - 关于如何检查子表是否具有某些多个值的雄辩或 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();
但我希望它只从购买表中获得未付款和取消状态的客户
解决方案
使用 SQL,您需要并且子句中group by customer_id
的条件将为您提供您想要的客户:count(distinct status) = 2
having
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
推荐阅读
- apache-flink - flink 检查点卡在收到 0 个字节的子任务上
- visual-studio - 有没有办法阻止 Visual Studio 撤消多个字符
- javascript - 全局变量不可访问
- objective-c - CFDictionaryContainsKey 和 CFDictionaryGetCountOfKey 有什么区别
- java - 未找到连接器的插件类加载器
- java - iText 使用 Vitrium 保护的用户名和密码打开 PDF
- tfs - 回滚/还原 TFS 中的特定/单个更改集而不影响以后的更改集
- ios - 广告 SDK 在没有 AppMeasurement 的情况下初始化
- powerbi - 无法在 Power BI 中登录或发布报表
- function - N位数的绝对减法