Check if all ancestors fulfill condition #249
-
I struggle to find a proper solution to only include models wehere all it's ancestors fulfill a certain condition. I came up with the following query, which works: $activePages = Page::query()
->where('active', true)
->withCount([
'ancestors as __total_ancestors_count',
'ancestors as __active_ancestors_count' => fn($query) => $query->where('active', true),
])
->havingRaw('__total_ancestors_count = __active_ancestors_count')
->get(); But I need to wrap this conditions in a logic group to be able to perform other conditions on the query. For this reason the "with count solution" does not work anymore: $activePagesWhitelist = [10, 20];
$activePages = Page::query()
->whereIn('id', $activePagesWhitelist)
// Not working since aggregates are not supported in logical groups.
->orWhere(
fn($query) => $query
->where('active', true)
->withCount([
'ancestors as __total_ancestors_count',
'ancestors as __active_ancestors_count' => fn($query) => $query->where('active', true),
])
->havingRaw('__total_ancestors_count = __active_ancestors_count')
)
->get(); Is there a better/proper way to archive this? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hi @jacobmllr95, Page::whereNotHas('ancestors', fn($query) => $query->where('active', false)) |
Beta Was this translation helpful? Give feedback.
Hi @jacobmllr95,
You could check the "opposite" - that a page doesn't have any inactive ancestors: