laravel-adjacency-list icon indicating copy to clipboard operation
laravel-adjacency-list copied to clipboard

Filter path

Open MiladAheshmeh opened this issue 2 years ago • 5 comments

How can I filter a path that visible = 0

users

id first_name last_name parent_id visible (0,1)

MiladAheshmeh avatar Jun 28 '22 10:06 MiladAheshmeh

$tree = User::withRecursiveQueryConstraint(function (Builder $query) {
   $query->where('users.visible', 1);
}, function () {
   return User::find(2)->descendants()
});

@staudenmeir

MiladAheshmeh avatar Jun 28 '22 11:06 MiladAheshmeh

Hi @MiladAheshmeh,

You need to remove the parentheses to execute the relationship query:

$tree = User::withRecursiveQueryConstraint(function (Builder $query) {
   $query->where('users.visible', 1);
}, function () {
   return User::find(2)->descendants;
});                                ^^

staudenmeir avatar Jun 28 '22 12:06 staudenmeir

same result @staudenmeir

MiladAheshmeh avatar Jun 28 '22 16:06 MiladAheshmeh

Database Screen Shot 1401-04-07 at 21 28 19

Code Screen Shot 1401-04-07 at 21 28 52

Result Screen Shot 1401-04-07 at 21 29 07

David is invisible so why Michael and David are in the result??

MiladAheshmeh avatar Jun 28 '22 17:06 MiladAheshmeh

You're right, the query doesn't catch invisible descendants on the first level (direct children). I'm looking into a solution.

In the meantime, combine it with the (internal) scope withRelationshipExpression():

$tree = User::withRecursiveQueryConstraint(function ($query) {
    $query->where('users.visible', 1);
}, function () {
    $constraint = function ($query) {
        $query->where('parent_id', 2)->where('visible', 1);
    };

    return User::withRelationshipExpression('desc', $constraint, 1);
})->pluck('first_name');

staudenmeir avatar Jul 04 '22 19:07 staudenmeir

Someone has a solution for this?

stephanesoares avatar Nov 07 '22 16:11 stephanesoares

apply the same constraint to the original query too, because the withRecursiveQueryConstraint does not apply to the immediate children and parents of the target user.

so either what Jonas did here or like so, it should work the same:

$tree = User::withRecursiveQueryConstraint(function (Builder $query) {
   $query->where('users.visible', 1);
}, function () {
   return User::find(2)->descendants()->where('users.visible', 1);
});

valentinomariotto avatar Nov 28 '22 09:11 valentinomariotto

I've released a new version with withQueryConstraint() that allows you to add a constraint to both the initial and the recursive query: https://github.com/staudenmeir/laravel-adjacency-list?tab=readme-ov-file#initial--recursive-query-constraints

$tree = User::withQueryConstraint(function (Builder $query) {
   $query->where('users.visible', 1);
}, function () {
   return User::find(2)->descendants;
});  

staudenmeir avatar Jan 18 '24 00:01 staudenmeir