2017-09-09 89 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列。

相关问题