I have table like this:
id | user | parent_id | level |
---------------------------------------------
1 | parent1 | 0 | 1
2 | parent2 | 0 | 1
3 | parent3 | 1 | 2
4 | child1 | 1 | 2
5 | child2 | 4 | 3
From child2 I would like to check if it belongs to parent1.
An obvious answer would be run a query from each level starting from child2 > check parent > check parent > until it is parent1. But that will be a lot of query to run. Like:
while ($parent = \DB::table('users')->where('parent_id', $child->parent_id)->first()) {
if ($checkparent->id == $parent->id) break; // found the checked parent
else $child = $parent;
}
Is there any way to run this with just one query? (Note: it will be more than 2 levels)
parent1 <-- to here parent2
/ \
parent3 child1
\
child2 <-- from here