You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel推荐系统层级限制问题:如何限制至3级推荐用户

Laravel推荐用户层级限制解决方案

你之前用limit(3)和take(3)无效,是因为这两个方法是限制单级查询返回的用户数量,而不是控制推荐用户的层级数。要实现最多3级推荐用户的查询,需要在递归逻辑中通过$currentLevel判断终止条件,具体修改如下:

修改后的代码

public function referralUsers($id, $currentLevel = 1)
{
    // 核心判断:当前层级超过3时,直接返回,停止递归
    if ($currentLevel > 3) {
        return $this->allusers;
    }

    $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;
}

逻辑说明

  1. 在referralUsers方法开头添加层级判断:当$currentLevel大于3时,直接返回已收集的用户数据,不再继续递归查询下一级推荐用户。
  2. 初始调用时$currentLevel默认为1,处理完第一级后层级递增为2,递归查询第二级;以此类推,直到层级达到3后,停止后续递归。

这样就能精准控制只获取最多3级的推荐用户,而不会无限递归下去。

内容的提问来源于stack exchange,提问作者Drunken M

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 04:10:16