这里希望返回的数据比较好看、好处理,而不是通过关联数据的方式返回。

    1. 使用分页查询中间表的数据
    2. 使用 array_map 取出需要的字段
    3. 查询真正需要返回的列表
    4. 返回 LengthAwarePaginator 对象
    1. public function fans($userId)
    2. {
    3. // 1.1 检查用户是否存在
    4. UserModel::mustExist(['id' => $userId, 'status' => BaseModel::ENABLED], '用户不存在或已被封禁');
    5. // 2.1 查 user_follow 表, 找出跟当前用户相关的记录
    6. $userFollows = UserFollowModel::where(['followed_user_id' => $userId])->paginate(request('pagesize', 20));
    7. // 2.2 查询本次需要查询的 user_id
    8. $ids = array_map(function ($item) {
    9. return $item->user_id;
    10. }, $userFollows->items());
    11. // 3.1 根据刚才得到的 user_id 查询 user
    12. $users = UserModel::whereIn('id', $ids)->get()->toArray();
    13. // 4.1 创建 LengthAwarePaginator 对象
    14. $result = new LengthAwarePaginator($users, $userFollows->total(), $userFollows->perPage(), $userFollows->currentPage());
    15. return $this->success($result);
    16. }