【问题标题】:Laravel: MYSQL check if child belongs to top level parent with one queryLaravel:MYSQL通过一个查询检查孩子是否属于顶级父母
【发布时间】: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


【解决方案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

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

【讨论】:

  • 这不是我要找的。每个用户都是同一个模型。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-22
  • 2016-05-13
相关资源
最近更新 更多