【问题标题】:Codeigniter Active Record where value in JSON objectCodeigniter Active Record 在 JSON 对象中的值
【发布时间】:2013-08-06 17:15:56
【问题描述】:

我有一个问题要问。首先,我有一个表,其中父母有parent_id0 和孩子有parent_id 相等的父母ID。 parent_id 的所有子记录存储为 json 编码数组(一个子记录可以有多个父记录)。

那么,当我传递一个父 id 时,如何获取父的所有孩子。我试过了,但它不起作用,我不知道。

代码如下:

function get_child_product($parent_id, $limit, $start) {
        $this -> db -> from('product');
        $this -> db -> where(json_decode('parent_id'), $parent_id);
        $this -> db -> limit($limit, $start);
        $this -> db -> order_by('order', 'asc');
        $this -> db -> order_by('id', 'desc');
        $query = $this -> db -> get();
        return $query -> result();
    }

问题解决了:

function get_child_product($parent_id, $limit, $start) {
        $this -> db -> from('product');
        $this -> db -> like('parent_id', '"' . $parent_id . '"');
        $this -> db -> limit($limit, $start);
        $this -> db -> order_by('order', 'asc');
        $this -> db -> order_by('id', 'desc');
        $query = $this -> db -> get();
        return $query -> result();
    }

【问题讨论】:

  • 你能再清楚一点吗?数据库中的 JSON 是什么?或者您是否正在向您的函数发送一组 id 以获取这些父母的所有孩子?
  • 是的,我将 parent_id 数组作为 JSON 存储在数据库中。

标签: mysql codeigniter


【解决方案1】:

如果我理解正确,您的数据库中有一个带有父关系的 JSON 编码数组,并且您只想获取某个父级的子级。问题是数据库中的 JSON 对象只不过是字符串,您不能在查询中动态解码它们并使用 where 子句。

你有两个选择:

1.查询所有孩子,然后使用 PHP 根据解码后的 JSON 过滤它们

2.使用mysqllike匹配json格式的字符串

function get_child_product($parent_id, $limit, $start) {
    return $this -> db -> from('product')
                    -> like('parent_id', '"parent_id":'.$parent_id)
                    -> limit($limit, $start)
                    -> order_by('order', 'asc')
                    -> order_by('id', 'desc')
                    -> get()
                    -> result();
}

请注意,like 参数应与 JSON 的语法匹配,因此如果您的 id 包含在 " 引号中,则将它们添加到参数中

【讨论】:

    【解决方案2】:

    你确定你不是故意的

    where('parent_id', decoded($parent_id));
    

    ?

    【讨论】:

      【解决方案3】:

      试试active recordswhere_in子句:

      function get_child_product($parent_id, $limit, $start) {
          $this -> db -> from('product');
          $this -> db -> where_in( parent_id, decoded($parent_id) ); #changes here
          $this -> db -> limit($limit, $start);
          $this -> db -> order_by('order', 'asc');
          $this -> db -> order_by('id', 'desc');
          $query = $this -> db -> get();
          return $query -> result();
      }
      

      【讨论】:

      • 'parent_id' 周围缺少引号。
      猜你喜欢
      • 2013-06-14
      • 1970-01-01
      • 2012-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多