【问题标题】:How to implement tree like structure in mysql and laravel如何在 mysql 和 laravel 中实现树状结构
【发布时间】:2018-02-18 03:10:09
【问题描述】:

一个问题在我脑海中盘旋了 2 天,想知道是否可以在 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个childers)"

链一直持续到 A 获得 40 的总引用。

简单来说,如果一个人推荐另一个人,那么它会得到 +1,他被推荐的父级也得到 +1,依此类推,直到父级达到 40,链继续。

我知道,这是用户和推荐人之间的一对多关系,我们可以使用数据透视表,但是,我们如何实现这种类型的逻辑。给我一些提示。谢谢。

【问题讨论】:

  • 就个人而言,我不会使用数据透视表,我只会在同一个表中添加一个referred_by 列。你想把这个逻辑放在哪里?你想要一个函数来计算给定用户推荐的人数或类似的东西吗?
  • 这意味着我们需要在referred_by上使用while循环并继续循环直到refered_by达到null?
  • 我只是想知道如何实现这种类型的逻辑,如果可以的话我想开发它。
  • 执行此操作的方法是运行查询以选择给定用户的所有“孩子”,然后在返回用户的查询中不断运行 where 以选择他们的“孩子”,直到您得到一个没有结果的查询。那么这将是一个计算“孩子”和“孩子的孩子”总数的情况。就个人而言,我会将其实现为递归方法,但如果您愿意,也可以循环执行。
  • 我已经添加了一个答案,希望对你有所帮助。

标签: php mysql laravel laravel-5 database-design


【解决方案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 列。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-27
    • 1970-01-01
    • 2010-12-28
    • 2016-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多