laravel-adjacency-list
laravel-adjacency-list copied to clipboard
Filter path
How can I filter a path that visible = 0
users
id first_name last_name parent_id visible (0,1)
$tree = User::withRecursiveQueryConstraint(function (Builder $query) {
$query->where('users.visible', 1);
}, function () {
return User::find(2)->descendants()
});
@staudenmeir
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;
}); ^^
same result @staudenmeir
Database
Code
Result
David is invisible so why Michael and David are in the result??
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');
Someone has a solution for this?
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);
});
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;
});