paginate分页常见问题

分页后的数据 使用集合的map方法过滤数据后, 分页的信息都没有了, 只有查询到的数据了 , 为什么?

代码如下:

//查询出来的分页数据 有打印是有分页信息的
$goods = Goods::query()
    ->join('goods_categories', 'goods_categories.id', '=', 'goods.category_id')
    ->join('users', 'users.id', '=', 'goods.user_id')
    ->where('goods.sale_type', $request->sale_type)
    ->orderBy($order_field, $order_type)
    ->when($category_name, function ($query)use ($category_name){
        $query->where('goods_categories.name', 'like', '%'.$category_name.'%');
    })
    ->leftJoin('user_authenticates as ua', 'ua.uid', '=', 'users.id')
    ->select([
        'goods.*',
        'users.name as user_name',
        'users.phone',
        'users.avatar',
        'ua.status',
        'goods_categories.name',
    ])
    ->paginate();

// 对分页数据进行处理
$goods = $goods->map(function($item){
    $attr_name_arr = [];
    if(!empty($item->goods_attrs)){
        $attr_name_arr = GoodsAttributeValue::query()
                            ->whereIn('id', $item->goods_attrs)
                            ->select(['id', 'name'])
                            ->get()
                            ->toArray();
        $attr_name_arr = array_column($attr_name_arr, 'name');
    }
    $item->goods_attri_name = implode(',', $attr_name_arr);
    return $item;
});

return $this->success($goods);

注: $this->success 是我写的trait里的方法

数据结果就是莫得了分页信息:

paginate分页常见问题

本作品采用《CC 协议》,转载必须注明作者和本文链接
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 10

代码呢

3年前 评论
czd1947 (楼主) 3年前
自由与温暖是遥不可及的梦想

你代码 能不能加 来标识 格式化一下 不然谁看的懂

3年前 评论
自由与温暖是遥不可及的梦想

```

3年前 评论
自由与温暖是遥不可及的梦想

集合《Laravel 8 中文文档》

map 处理过后是返回新的集合 而不是原先的集合.所以没有分页
3年前 评论

$goods->map() 触发Illuminate\Pagination\LengthAwarePaginator魔术方法 __call会获取到当前数据的集合(不包含分页信息)Illuminate\Database\Eloquent\Collection进行处理然后返回该Collection 对象。

3年前 评论

改成 foreach 或者 each,应该就行了

3年前 评论
$list = ...->paginate(10);

$list->getCollection()->transform(function($res){
   return ...
}

使用这个代码代替 map 的功能

3年前 评论
    //记录列表
    $one = UserRelation::with(['user'])->withCount('parent as huoban') 
            ->where($where)
            ->paginate(15);

    $one->map(function($item,$key) use($user){    
        $item->income = RebateLog::where(['rebate_user_id'=> $user->id,'user_id'=>$item['user_id'],'rebate_status'=>1])->sum('rebate_price');   
        return $item;
    });  

我的有分页哦

3年前 评论

如果是最新的 laravel 版本可以用through方法

    /**
     * Transform each item in the slice of items using a callback.
     *
     * @param  callable  $callback
     * @return $this
     */
    public function through(callable $callback)
    {
        $this->items->transform($callback);

        return $this;
    }
3年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!