【发布时间】:2017-06-12 21:19:33
【问题描述】:
我有这样的表:
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
【问题讨论】:
-
dba.stackexchange.com/questions/46393/… 不适用于 mysql。 Tbh,这是一个微优化。由于您已经在使用 laravel,因此对数据库的更多请求不应该是一个大问题。假设
id是主键,查询应该很快。 -
@AlexBlex:500 个关卡怎么样?
-
然后重新考虑数据模型或存储引擎。 Mysql 不适合。
-
详细说明,您可以在模型中添加
top_parent字段,或者使用例如Postgres:stackoverflow.com/questions/14659856/… -
为了清楚起见,任何 SQL 解决方案都会执行 '500' 查询,即使它是在存储过程/udf 中编码并且看起来像来自 laravel 端的“单一”查询。如果你处理非常大的树,你最好使用为它设计的东西,例如。 neo4j 或任何其他图形数据库。
标签: php mysql laravel-5 eloquent