【发布时间】:2020-06-15 20:50:10
【问题描述】:
有什么方法可以通过其父 id 获取左右子节点的总数,直到子级别的“N”个。
这是我的用户表,我在其中存储带有腿(左/右)位置的父子信息
地点:
-
referral_id:是子用户的父用户id -
left_child_id: 是左腿加入用户的子用户id -
right_child_id: 是右腿加入用户的子用户的id。 -
position_to_referral: 是他加入父用户的位置名称(左/右腿)
欢迎任何帮助或任何建议。
我可以使用下面的 php 代码获取计数,但我想直接从 mysql 获取计数
function countChildren($parentId, $Nlevel, $tempLevel = 0)
{
if ($tempLevel < $Nlevel) {
$tempLevel = $tempLevel + 1;
$children = User::where('referral_id', $parentId)->get()->pluck('id');
$count = count($children);
foreach ($children as $userId) {
$count += $this->countChildren($userId, $Nlevel, $tempLevel);
}
return $count;
}
}
编辑 2
更新了代码以在有或没有 N 级的情况下向左、向右
public function countChildren($parentId, $Nlevel = 0, $legPosition = 0, $tempLevel = 0)
{
if ($Nlevel) {
if ($tempLevel < $Nlevel) {
$tempLevel = $tempLevel + 1;
if ($tempLevel == 1 && $legPosition) {
$children = User::where('referral_id', $parentId)
->where('position_to_referral', $legPosition)
->get()->pluck('id');
} else {
$children = User::where('referral_id', $parentId)->get()->pluck('id');
}
$count = count($children);
foreach ($children as $userId) {
$count += $this->countChildren($userId, $Nlevel, $legPosition, $tempLevel);
}
return $count;
}
} else {
if ($legPosition) {
$children = User::where('referral_id', $parentId)
->where('position_to_referral', $legPosition)
->get()->pluck('id');
} else {
$children = User::where('referral_id', $parentId)->get()->pluck('id');
}
$count = count($children);
foreach ($children as $userId) {
$count += $this->countChildren($userId);
}
return $count;
}
}
调用上面的函数来获取计数:
$total = $profileService->countChildren(1); // get total children count of user_id = 1
$totalWith3Level = $profileService->countChildren(1, 3); // get total children count till 3 level
$totalLeft = $profileService->countChildren(1, '', 'left'); // get total children count of left leg
$totalRight = $profileService->countChildren(1, '', 'right'); // get total children count of right leg
$totalLeftWith3Level = $profileService->countChildren(1, 3, 'left'); // get total children count of left leg till 3 level
$totalRightWith3Level = $profileService->countChildren(1, 3, 'right'); // get total children count of right leg till 3 level
【问题讨论】:
-
请添加例外的输出以及您到目前为止所尝试的内容。
-
@AkhileshMishra 我用尝试过的解决方案更新了我的问题
-
请同时发布预期输出
标签: php mysql laravel binary-tree