2017-09-09 88 views
0

我腦海中出現了兩天的問題,並想知道是否可以在laravel和MySQL中實現這種類型的樹結構。如何在mysql和laravel中實現類似樹的結構

enter image description here

(首先,看一看圖像連接。謝謝)

假設我們的平臺使用參考系統,和最初,用戶 '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(他引用beacuase 9 childers)「

鏈條繼續,直到A得到總數爲40。

簡單,如果一個人指另一人則是會得到+1和它的父人,他被請參閱還可以獲得+1依此類推,直到父達到40,鏈繼續。

我知道,這是一個用戶之間一對多的關係,是指我們可以使用數據透視表,但是,如何才能實現這種類型的邏輯。給我一些提示。謝謝。

+0

就個人而言,我不會使用數據透視表,我只是在同一個表中添加一個'referenced_by'列。你想把這個邏輯放在哪裏?你想要一個函數來計算給定用戶提及的人數或類似的人數嗎? – Jonathon

+0

這意味着我們需要在refer_by上使用while循環,並繼續前進,直到referenced_by達到null爲止? – Dishu

+0

我只是想知道如何實現這種類型的邏輯,如果有可能我想開發它。 – Dishu

回答

1

我寫出來的東西,應該有希望幫助您完成此,使用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列。

相關問題