Laravel:MYSQL检查子项是否属于具有一个查询的顶级父级

时间:2017-01-27 08:38:47

标签: php mysql laravel-5 eloquent

我有这样的表:

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 

来自 child2 我想检查它是否属于 parent1

一个明显的答案是从 child2 >开始从每个级别运行查询检查父母>检查父母>直到 parent1 。但这将是很多查询运行。像:

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;
}

有没有办法只用一个查询来运行它? (注意:它将超过2个级别)

parent1  <-- to here            parent2
/      \
parent3  child1
           \
          child2 <-- from here

1 个答案:

答案 0 :(得分:-1)

我认为你正在寻找这个:

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();

有关详情,请点击此处 - https://laravel.com/docs/5.3/eloquent-relationships

您需要确保在模型中正确配置关系。