简体   繁体   中英

Laravel: MYSQL check if child belongs to top level parent with one query

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

I think you are looking for this:

Nested has statements may also be constructed using "dot" notation. For example, you may retrieve all posts that have at least one comment and vote:

// Retrieve all posts that have at least one comment with votes...
$posts = Post::has('comments.votes')->get();

For more info check here - https://laravel.com/docs/5.3/eloquent-relationships

You need to make sure that the relationship is configured properly in the models.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM