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

Laravel 7如何基于JSON格式的品牌ID搜索商品?

实现JSON格式品牌字段的商品搜索

你的问题核心是商品表的brand_id字段存储为JSON数组,原代码的精确匹配无法命中数组中的值,需要改用Laravel针对JSON字段的查询方法:

直接修改控制器中的条件判断代码:

$products = ProductStock::join('products','product_stocks.product_id', '=', 'products.id')
    ->where('user_id', Auth::user()->id)
    ->where('published', '1')
    ->select('products.*','product_stocks.id as stock_id','product_stocks.variant','product_stocks.price as stock_price', 'product_stocks.qty as stock_qty', 'product_stocks.image as stock_image')
    ->orderBy('products.created_at', 'desc');
    
if($request->brand != null){
    // 使用whereJsonContains检查品牌ID是否存在于JSON数组中
    $products = $products->whereJsonContains('products.brand_id', $request->brand);
}

关键说明

  • whereJsonContains是Laravel内置的JSON字段查询方法,会自动生成对应数据库的JSON查询语句(比如MySQL的JSON_CONTAINS),能准确判断指定品牌ID是否在brand_id的JSON数组内。
  • 注意保证传入的$request->brand类型和JSON数组内的元素类型一致(示例中数组元素是字符串类型,所以参数也需为字符串,避免类型不匹配导致查询无结果)。
  • 该方法要求数据库支持JSON函数(如MySQL 5.7及以上版本、PostgreSQL等)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 14:10:28