Php Laravel:MYSQL通过一个查询检查子项是否属于顶级父项
我有这样的桌子:Php Laravel:MYSQL通过一个查询检查子项是否属于顶级父项,php,mysql,laravel-5,eloquent,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
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我想你在找这个:
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();
欲了解更多信息,请点击此处-
您需要确保在模型中正确配置了关系。这不是我想要的。每个用户都是相同的型号。使用mysql是不可行的。Tbh,这是一个微观优化。因为您已经在使用laravel,所以对数据库的更多请求应该不是什么大问题。假设id
是主键,查询应该很快。@AlexBlex:500级怎么样?然后重新考虑数据模型或存储引擎。Mysql不适合这个目的。为了详细说明,您可以向模型中添加top\u parent
字段,或者使用例如Postgres:为了清楚起见,任何SQL解决方案都会执行“500”查询,即使它是在存储过程/udf中编码的,看起来像是来自laravel端的“单个”查询。如果你处理的是真正的大树,你最好使用为它设计的东西,例如neo4j或任何其他图形数据库。
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();