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

A question struck in my mind for 2 days and wondering whether it is possible to implement this type of tree structure in laravel and MySQL.

enter image description here

(First, take a look at the image attached. Thanks)

Suppose our platform uses refer system, and initially, a user 'A' join. Now, this user 'A' further refers 3 persons 'B','C','D'. Now, the total refer on A is 3 (because it refers 3 persons).

Now, let B further refers 'E','F' and 'C' further refers 'G','H', 'I' and 'D' refers 0. So, now refer of each person is "D = 0", "C = 3", "B = 2". and these refers will also add up on "A". So, it has "A = 8".

Now, 'G' refers 'J', so 'G' gets +1 and 'C' also gets +1 and 'C' is referred by 'A', so 'A' also gets +1. Now, total refer to each person is : "j = 0","G=1","H=0","I=0", "D=0","E=0","f=0","B=2","C=4 (beacuse G refers J also)","A=9(beacuase 9 childers are refered by him)"

The chain continues until A gets total refer of 40.

In simple, if a person refers another person then it will get +1 and it's parent whom he gets refer also get +1 and so on until parent reaches 40, the chain continues.

I know, this is One-Many relationship between a user and refer and we can use a pivot table, but, How can we implement this type of logic. Give me some hints. Thanks.

I have written out something that should hopefully help you with this, using a while loop.

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();
}

You can use it like this:

$user = User::find(1);

$totalReferred = $this->totalReferredBy($user);

Then if your application does something when the user reaches 40 or more referred, you can just do:

if ($this->totalReferredBy($user) > 40) {
    // Do something
}

This assumes that you have a referred_by column on the users table.