Codeigniter Active Record where value in JSON object

落花浮王杯 提交于 2021-02-11 08:06:38

问题


I have a question to ask. Firstly, I have a table, where the parent has parent_id is 0 and the child has parent_id equal parent id. parent_id of all children are stored as a json encoded array (one child record can have many parents).

So, how can I get all the children of the parent when I pass one parent id. I tried but it won't work and I don't have a clue.

Here's the code:

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();
    }

Problem solved:

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();
    }

回答1:


If I understand correctly you have a JSON encoded array in your database with the parent relationship and you want to get only children of a certain parent. The thing is that JSON objects in a database are nothing more than strings, you cannot dynamically decode them in the query and use a where clause.

You have two options:

1.Query all your children then use PHP to filter them based on the decoded JSON

2.Use mysql like to match a string in json format

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();
}

Note that the like parameter should match the syntax of your JSON so if you're ids are wrapped in " quotes, then add them to the parameter




回答2:


Are you sure you don't mean

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

?




回答3:


Try where_in clause of active records:

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();
}


来源:https://stackoverflow.com/questions/18086465/codeigniter-active-record-where-value-in-json-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!