[英]How to implement tree like structure in mysql and laravel
我想了兩天的問題,想知道是否有可能在laravel和MySQL中實現這種樹結構。
(首先,查看附帶的圖像。謝謝)
假設我們的平台使用參照系統,並且最初使用用戶“ A”加入。 現在,該用戶“ A”還指3個人“ B”,“ C”,“ D”。 現在,A上的總推薦數為3(因為它引用了3個人)。
現在,讓B進一步引用'E','F'和'C'進一步引用'G','H','I'和'D'引用0。因此,現在每個人的引用是“ D = 0” ,“ C = 3”,“ B = 2”。 這些引用也將加到“ A”上。 因此,它具有“ A = 8”。
現在,“ G”表示“ J”,因此“ G”得到+1,而“ C”也得到+1,而“ C”由“ A”表示,因此“ A”也得到+1。 現在,每個人所指的總數是:“ j = 0”,“ G = 1”,“ H = 0”,“ I = 0”,“ D = 0”,“ E = 0”,“ f = 0” ,“ B = 2”,“ C = 4(因為G也指J)”,“ A = 9(因為9個孩子由他指代)”
鏈條一直持續到A獲得總推薦40。
簡單來說,如果一個人推薦另一個人,那么該人將獲得+1,而他所推薦的父母也將獲得+1,依此類推,直到父母達到40歲為止,這條鏈將繼續。
我知道,這是用戶和引薦之間的一對多關系,我們可以使用數據透視表,但是,如何實現這種類型的邏輯。 給我一些提示。 謝謝。
我已經寫了一些東西,希望可以通過while
循環來幫助您。
public function totalReferredBy(User $user)
{
// Initialise the queue to contain only the provided user
$queue = collect([$user]);
// This collection will eventually contain all of the "child"/referred users
$results = collect();
while ($queue->isNotEmpty() > 0) {
// Run a where in query to select all the referred users of the users in the queue.
$referredUsers = User::whereIn('referred_by', $queue->pluck('id'))->get();
// Merge the referredUsers we have found in the database with the results collection, so we can later count.
$results = $results->merge($referredUsers);
// Make the referredUsers we have just found in the database, the new queue. If the query did not return any
// referred users, the queue count would be 0 and the loop will exit.
$queue = $referredUsers;
}
// Now we should have all of the given user's "children" and "children of children" in the $results collection.
// We just need to return the count of that collection to get the total number of users that have been referred.
return $results->count();
}
您可以像這樣使用它:
$user = User::find(1);
$totalReferred = $this->totalReferredBy($user);
然后,如果您的應用程序在用戶達到40個或更多推薦人數時執行了某些操作,則可以執行以下操作:
if ($this->totalReferredBy($user) > 40) {
// Do something
}
假設您在users
表上有一個referred_by
列。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.