[英]Laravel: MYSQL check if child belongs to top level parent with one query
我有这样的表:
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 > check parent> check parent>到每个级别运行一个查询,直到它是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
我认为您正在寻找:
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
您需要确保在模型中正确配置了关系。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.