我有一个名为users
的数据库表
此表有两列(很重要(
uuid
和parentUuid
以下是该表的规则:
- 如果用户邀请其他用户,则
parentUuid
列的受邀用户等于邀请者的uuid
。 - 如果未邀请用户,则
null
其parentUuid
列 - 可以有无限级别的用户。
我想做的是,创建一个函数function counter($levels, $uuid){}
调用计数器时(假设 $levels = 3(
我希望该函数返回一个数组看来
array(0 => 200, 1 => 600, 2 => 1800);
所以基本的想法是我希望它倒计时,对于$levels
级别,用户下的树中有多少用户。
最好的方法是什么?
我会扩展您的用户表以包含一个"级别"列,该列指示用户从根目录开始的级别深度。 这样,当添加新用户时,他们的级别只会设置为父级的级别 + 1。
我知道这与您要求的解决方案略有不同,但是从不存储用户级别的表中获取所需数据的遍历过程充其量是棘手的,并且执行时间可能很长。 这似乎是一个很好的例子,其中最好的解决方案是对架构进行轻微修改。
您正在查看的是使用邻接列表模型存储在树中的分层数据。这很难扩展。尝试将其转换为嵌套集。区别是什么以及如何构建数据在这里得到了很好的解释:http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/
SAP 几乎在表的结构中到处都使用层次结构:
首先,您需要确保您的条目列表具有唯一标识符 UnID,即使您所需的信息位不是 UnID。UnID 可以是数字,以便于递增。
然后,当您将项目添加到层次结构表时,应按以下格式存储它们:
NodeID
Note: 0 is always the root nodeID. Any other entry is the UnId of the new entry. It can never be null
ParentID
Note: this is the UnID of the parent that you want to attribute to the new entry. It can never be null
ChildId
Note: this can be null. It is updated only when this New entry gets to be a parent.
NextId
Note: this is the important one. It determines which child is next in the sequence of children below the parent. The last one in the sequence is always null
Level
Note: this ensures that a UnID cannot be the parent at more than one level.
您将需要一些程序逻辑来消除在此处某处注释中提到的创建循环引用的尝试,但这意味着当引用发生时,您必须更新层次结构表中的三条记录:新条目、父项和父项的最后一个子项(带有 nextID(,以确保金字塔正确。
方法可以在数据库中存储分层数据。我建议使用物化路径。如果做不到这一点,嵌套集和邻接列表也可以工作。
https://communities.bmc.com/communities/docs/DOC-9902