I try to make referral query limit to 3 level of users referral system. The original codes give unlimited level of referrals.
public function referralUsers($id, $currentLevel = 1)
{
$users = $this->getUsers($id);
if ($users['status']) {
$this->allusers[$currentLevel] = $users['user'];
$currentLevel++;
$this->referralUsers($users['ids'], $currentLevel);
}
return $this->allusers;
}
public function getUsers($id)
{
if (isset($id)) {
$data['user'] = User::whereIn('referral_id', $id)->get(['id', 'firstname', 'lastname', 'username', 'email', 'phone_code', 'phone', 'referral_id', 'created_at']);
if (count($data['user']) > 0) {
$data['status'] = true;
$data['ids'] = $data['user']->pluck('id');
return $data;
}
}
$data['status'] = false;
return $data;
}
I tried to limit the db query by adding ->limit(3)
and ->take(3)
but not working
$data['user'] = User::whereIn('referral_id', $id)->limit(3)->get(['id', 'firstname', 'lastname', 'username', 'email', 'phone_code', 'phone', 'referral_id', 'created_at']);
and
$data['user'] = User::whereIn('referral_id', $id)->take(3)->get(['id', 'firstname', 'lastname', 'username', 'email', 'phone_code', 'phone', 'referral_id', 'created_at']);
If I can’t limit the db query, how to limit the result in the $currentLevel++
I am new to laravel codes.
Thanks!
2
Answers
I posted this answer based on a discussion with @Tom Lewis in the comments section. Hopefully this answer can be useful for whom wants to build a limited tiered referral system.
My script by default uses an unlimited referral system and I want to limit it to a maximum of 3 levels.
The dB query recursively use
whereIn
to search for thereferral_id
in any level of the referral database.User::whereIn('referral_id', $id)->get
and then return the result as$currentLevel
.It seems like limiting the dB query itself is not a good approach, so I try to focusing on limiting the level after the query result at the
$currentLevel
.The solution end up very simple, I just need to limit the
$currentLevel
as my need to 3.With this modification, the referralUsers function will stop recursive calls once it reaches the third level of referrals, effectively limiting the query to 3 levels.