onpage-dev / onpage-php

4 stars 5 forks source link

A question on filterRelation #6

Closed zsavajji closed 10 months ago

zsavajji commented 1 year ago

Hi! I need to filter some elements in a hierarchy based on the presence of a field in one of the children of the subrelation. I am now doing:

$query = query('resource')
    ->with('children')
    ->filterRelation('children', fn (QueryBuilder $q) =>
        $q->whereHas('children.relation')
    );

The result is correct, but i cannot filter out the elements which returned with empty children. I thought that doing something like

$query = query('resource')
    ->with('children')
    ->filterRelation('children', fn (QueryBuilder $q) =>
        $q->whereHas('children.relation')
    )
    ->whereHas('children');

would work as expected, but it's not. It's this the intended behavior?

Thank you!

gufoe commented 1 year ago

Hello @zsavajji sorry for the delay. Unluckily you will have to write the same filter twice, you can store in a variable to make it more readable:

$filter = fn (QueryBuilder $q) => $q->whereHas('children.relation');
$query = query('resource')
    ->with('children')
    ->filterRelation('children', $filter)
    ->whereHas('children', $filter);

But note that it might be better to create the filter directly in On Page (we call them Views) and apply it to the API token so that you can simply query the resource without adding any filter to your code, and the data will be filtered automatically before it is returned to you.