这里希望返回的数据比较好看、好处理,而不是通过关联数据的方式返回。
- 使用分页查询中间表的数据
- 使用 array_map 取出需要的字段
- 查询真正需要返回的列表
- 返回 LengthAwarePaginator 对象
public function fans($userId)
{
// 1.1 检查用户是否存在
UserModel::mustExist(['id' => $userId, 'status' => BaseModel::ENABLED], '用户不存在或已被封禁');
// 2.1 查 user_follow 表, 找出跟当前用户相关的记录
$userFollows = UserFollowModel::where(['followed_user_id' => $userId])->paginate(request('pagesize', 20));
// 2.2 查询本次需要查询的 user_id
$ids = array_map(function ($item) {
return $item->user_id;
}, $userFollows->items());
// 3.1 根据刚才得到的 user_id 查询 user
$users = UserModel::whereIn('id', $ids)->get()->toArray();
// 4.1 创建 LengthAwarePaginator 对象
$result = new LengthAwarePaginator($users, $userFollows->total(), $userFollows->perPage(), $userFollows->currentPage());
return $this->success($result);
}