gpt4 book ai didi

php - 如何在mysql和laravel中实现树状结构

转载 作者:行者123 更新时间:2023-11-29 10:37:39 25 4
gpt4 key购买 nike

一个问题在我脑海中浮现了两天,想知道是否可以在 Laravel 和 MySQL 中实现这种类型的树结构。

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(因为他引用了9个 child )"

这个链一直持续到 A 获得总引用数 40。

简单来说,如果一个人推荐另一个人,那么它会获得 +1,而他被推荐的 parent 也会获得 +1,依此类推,直到 parent 达到 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 列。

关于php - 如何在mysql和laravel中实现树状结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46129216/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com