Laravel 返回一个生成器,其每个关系';s模型符合特定条件
我有一个订单模型和一个交易模型。订单可以有一个或多个交易 我想要那些每个交易状态都是“待定”的订单 我尝试实现如下所示:Laravel 返回一个生成器,其每个关系';s模型符合特定条件,laravel,eloquent,laravel-8,Laravel,Eloquent,Laravel 8,我有一个订单模型和一个交易模型。订单可以有一个或多个交易 我想要那些每个交易状态都是“待定”的订单 我尝试实现如下所示: $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->whereHas('transactions', function ($query) {
$query->where('status', 'Pending');
});
}
这将返回至少有一个事务处于“挂起”状态的订单。
但我希望其每个事务的状态都为“待定”的订单。要查找其所有事务都标记为待定的订单,您将需要使用
中的条件聚合对待定事务进行计数,然后检查事务的总计数是否等于待定事务计数
Order::withCount([
'transactions',
'transactions as pending_count' => function ($query) {
$query->select(DB::raw("sum(case when status = 'pending' then 1 else 0 end)"));
}
])
->with('transactions')
->havingRaw('transactions_count = pending_count')
->get();
我认为你可以用相反的方法轻松地做到这一点,比如:
$builder = Order::with('transactions')->latest('id');
if($condition)
{
$builder = $builder->has('transactions')
->whereDoesntHave('transactions', function ($query) {
$query->where('status','!=', 'Pending');
});
}
$result = $builder->get();
“has”方法确保存在事务,而where不确保所有事务都处于挂起状态