[英]In mysql Get the count of left and right child of root user
有什么方法可以通過其父 ID 獲取左右子節點的總數,直到子級別的“N”個。
這是我的用戶表,我在其中存儲帶有腿(左/右)position 的父子信息
在哪里:
referral_id
: 是子用戶的父用戶的idleft_child_id
:是左腿加入用戶的子用戶的idright_child_id
:是右腿加入用戶的子用戶的 id。position_to_referral
: 是他加入父用戶的 position 名稱(左/右腿)歡迎任何幫助或任何建議。
我可以使用下面的 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;
}
}
調用上面的 function 得到計數:
$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
嵌套集 model 不是更有意義嗎?
1 A 14
|
+-------+--------+
| |
2 B 7 8 C 13
| |
+---+---+ +----+----+
| | | |
3 D 4 5 E 6 9 F 10 11 G 12
user lft rgt
A 1 14
B 2 7
C 8 13
D 3 4
E 5 6
F 9 10
G 11 12
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.