gpt4 book ai didi

php - 拉维尔 : MYSQL check if child belongs to top level parent with one query

转载 作者:行者123 更新时间:2023-11-30 23:45:09 25 4
gpt4 key购买 nike

我有这样的表:

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

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

关于php - 拉维尔 : MYSQL check if child belongs to top level parent with one query,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41889797/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com