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

Laravel 9中whereIn结合paginate无返回结果问题求助

Laravel 9分页结合whereIn无结果的排查与解决

可能的问题及解决办法

1. 分页返回的JSON结构与集合存在差异

Laravel的paginate()返回的是LengthAwarePaginator对象,转为JSON后包含data(当前页实际数据)、links(分页链接)、meta(分页元信息)等字段;而get()返回的是普通Collection集合,直接是数据数组。

如果前端直接读取返回的locations而不是locations.data,就会看不到数据。可以调整返回方式,明确拆分数据与分页信息:

public function get_all_locations(Request $request){
    $locations = Locations::latest()->whereIn('company_id', [$request->company_id])->paginate(1);
    return response()->json([
        'locations' => $locations->items(), // 仅返回当前页的数据数组
        'pagination' => [
            'total' => $locations->total(),
            'current_page' => $locations->currentPage(),
            'per_page' => $locations->perPage(),
            'last_page' => $locations->lastPage()
        ]
    ],200);
}

或者让前端通过locations.data字段获取实际数据。

2. 排查latest()排序的影响

latest()默认按created_at倒序排列数据,如果符合条件的记录排序后,默认第一页没有数据(比如数据被分到了后续页码,但未传入page参数默认取第1页),也会出现无结果的情况。可以去掉latest()测试,或指定明确的排序字段:

$locations = Locations::whereIn('company_id', [$request->company_id])->orderBy('id', 'desc')->paginate(1);

3. 简化whereIn查询(规范写法)

当whereIn的数组仅包含单个值时,直接使用where()更高效规范:

$locations = Locations::latest()->where('company_id', $request->company_id)->paginate(1);

4. 检查请求的page参数是否异常

如果前端传入了page参数(比如page=2),但符合条件的总数据量不足2页,就会返回空数据。可以在控制器中打印$request->page确认参数,或强制指定默认页码:

$locations = Locations::latest()->where('company_id', $request->company_id)->paginate(1, ['*'], 'page', $request->page ?? 1);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 12:21:49