Saturday 3 October 2020

laravel recursion display referred users by level/depth

So I'm working with affiliate and doing fine with registration and saving who referred to a user, now I'm struggling in showing those users with referrals by Level.

Level is not save in the database, I'm thinking of it as incrementing in the logic area?

users table structure

id |  name  | sponsor_id |
 1 |  John  |    NULL    |
 2 |  Jane  |      1     |
 3 |  Jess  |      1     |
 4 |  Joe   |      2     |

so the output I want should be like this:

I am John, level 1 are who's sponsor_id is mine, and level 2 are who's sponsor_id is id's of whom I invited.

ID |  Name  |  Level  |
2  |  Jane  |    1    | 
3  |  Jess  |    1    |
4  |  Joe   |    2    |

where Jane & Jess's sponsor_id is mine, and Joe's sponsor_id is Jess

User has sponsor

public function sponsor()
{
    return $this->belongsTo('App\User', 'sponsor_id');
}

User has referrals

public function referrals()
{
    return $this->hasMany('App\User', 'sponsor_id');
}


from laravel recursion display referred users by level/depth

No comments:

Post a Comment