我有一个订单模型和一个交易模型。一个订单可以有一个或多个交易。
我想要那些每个交易状态都是“待处理”的订单。
我试着像下面这样实现:
$builder = Order::with('transactions')->latest('id');
if(condition)
{
$builder->whereHas('transactions', function ($query) {
$query->where('status', 'Pending');
});
}
这将返回那些至少有一笔交易处于“待定”状态的订单。 但我想要那些每笔交易都处于“待定”状态的订单。
最佳答案
我认为您可以使用相反的方式轻松做到这一点,例如:
$builder = Order::with('transactions')->latest('id');
if($condition)
{
$builder = $builder->has('transactions')
->whereDoesntHave('transactions', function ($query) {
$query->where('status','!=', 'Pending');
});
}
$result = $builder->get();
'has' 方法确保存在交易,而 whereDoesntHave 确保所有交易都处于挂起状态
关于laravel - 返回一个构建器,其每个关系的模型都匹配特定条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66348373/