现在有张表,id、yarn_attr等其他字段,其中yarn_attr存储的格式是json。现在需要根据条件,查询json对象里面的值,该怎么操作?

yarn_attr的格式如下:

{
     \"dye_id\": null,
     \"dye_name\": \"\",
     \"light_id\": 39, 
     \"cotton_id\": null,
     \"dye_index\": -1,
     \"light_name\": \"全啞光\",
     \"cotton_name\": \"\", 
    \"light_index\": 1,
     \"cotton_index\": -1
}

查询代码片段如下:

$where = array_filter($where); //过滤掉空值
//组成SQL语句
$yarn_attr = $data[\'yarn_attr\'];
$sql = \"\";
foreach ($yarn_attr as $key => $value) {
    if (!empty($value)) {
          //非数字需要加引号
          if (!is_numeric($value)) {
               $sql .= \'yarn_attr->\"$.\' . $key . \'\"=\"\' . $value . \'\" and \';
          } else {
               $sql .= \'yarn_attr->\"$.\' . $key . \'\"=\' . $value . \' and \';
          }
   }
 }
 $sql = rtrim($sql, \" and \");
 $count = YarnCheck::query()->where($where)->whereRaw($sql)->whereNull(\'deleted_at\')->count();

 

收藏 打印