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

Laravel 9中如何用Ajax传入的category_id数组构建Where查询条件

解决方法

在Laravel中,要匹配字段值处于数组范围内的记录,不能使用普通的where方法(该方法仅匹配单个值),需改用whereIn方法,具体修改如下:

public function productCategoryList(Request $request)
{
    // 接收前端传入的分类ID数组
    $categoryIds = $request->status;
    
    // 使用whereIn查询category_id在目标数组内的产品数据
    $data = Products::whereIn('category_id', $categoryIds)->get();
    
    return $data;
}

额外注意事项

  • 需确保前端Ajax请求里的status参数是标准数组格式(比如请求参数为status[]=1&status[]=2或JSON数组);如果前端传的是逗号分隔的字符串(如"1,2,3"),需先转换为数组:
    $categoryIds = explode(',', $request->status);
    
  • 可添加参数验证,避免空数组或非法值传入:
    $request->validate([
        'status' => 'required|array',
        'status.*' => 'integer|exists:categories,id' // 验证每个ID都是合法的分类ID
    ]);
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 08:33:10