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

Laravel中如何查询匹配用户JSON数组邮编的订单数据?

问题分析与解决方案

你当前的代码误用了查询方法:whereJsonContains 是用来检查JSON类型字段是否包含指定值的,而你的订单表 pin_code 是普通字符串字段,用户表的 pin_codes 是JSON格式的数组,正确的做法是将JSON数组转为PHP数组后,使用 whereIn 进行查询。

修正步骤:

  1. 确保用户表的 pin_codes 字段被解析为PHP数组:

    • 如果你的 User 模型中没有配置字段类型转换,需要手动将JSON字符串解码为数组:
      $pincodes = json_decode(Auth::user()->pin_codes, true);
      
    • 若已在 User 模型中添加了类型转换(推荐做法):
      // 在User模型中
      protected $casts = [
          'pin_codes' => 'array',
      ];
      
      此时 Auth::user()->pin_codes 会直接返回PHP数组,无需手动解码。
  2. 使用 whereIn 查询订单表中 pin_code 属于该数组的记录:

修正后的完整代码

public function orders()
{
    // 若User模型未配置$casts,需替换为json_decode那行
    $pincodes = Auth::user()->pin_codes;
    // 未配置$casts时用下面这行:
    // $pincodes = json_decode(Auth::user()->pin_codes, true);
        
    $order_list = Order::whereIn('pin_code', $pincodes)->get();
    return view('delivery.orders', compact('order_list'));
}

关键说明

  • whereIn 用于匹配字段值存在于指定数组中的记录,正好符合你的需求:筛选订单表中 pin_code 属于用户pincodes数组的订单。
  • whereJsonContains 适用于订单表的 pin_code 本身是JSON数组的场景(比如订单表pin_code存的是["712401", "xxx"]),但你的场景中订单表pin_code是单个字符串,因此不适用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 23:55:18