请教一个多对多查询并且分页的问题

我有如下表:
users

  • id

card

  • id_card
  • name

site

  • staff_id

info:

  • mobile

这几张表都是关联上users表的。
我想实现将其所有人的关联查询出来。再进行分页。我是这样实现的。

        $person = $this->repository->query->with(['card:id_card,name', 'site:staff_id', 'information:mobile'])->paginate(10);

但似乎返回的数据不是我想要的,我想要的格式是

"data":{
    list:[
    {
    id:1,
    id_card: 51103154xxxxxxxxx,
    name: '张三',
    staff_id:'123456',
    mobile:'13548975454',
    },
        {
    id:1,
    id_card: 51103154xxxxxxxxx,
    name: '张三',
    staff_id:'123456',
    mobile:'13548975454',
    },
    ]
}
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
最佳答案

先分页,然后用 resources 处理成你想要的数据

// 查询
$person = UserResource::collection($this->repository->query->with(['card:id_card,name', 'site:staff_id', 'information:mobile'])->paginate(10))->resource;
// resource

class UserResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'id_card' => $this->card->id_card,
            'name' => $this->card->name,
            'staff_id' => $this->site->staff_id,
            'mobile' => $this->information->mobile,
        ];
    }
}
2年前 评论
讨论数量: 5

paginate 方法是包含 meta 分页信息的,不想包含分页信息的话,自行使用 offset 查询

博客:Laravel 中 offset,limit 或 skip , take 的使用

2年前 评论
浪里小白龙 (楼主) 2年前

with()还能这么用,学到了,不过看文档有一句话:

注意:在使用这个特性时,一定要在要获取的列的列表中包含 id 列。

2年前 评论

需要重新对分页data数据进行你自己需要的组装

2年前 评论

先分页,然后用 resources 处理成你想要的数据

// 查询
$person = UserResource::collection($this->repository->query->with(['card:id_card,name', 'site:staff_id', 'information:mobile'])->paginate(10))->resource;
// resource

class UserResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'id_card' => $this->card->id_card,
            'name' => $this->card->name,
            'staff_id' => $this->site->staff_id,
            'mobile' => $this->information->mobile,
        ];
    }
}
2年前 评论

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