如何将查询结果提供给CodeIgniter中的where条件?

时间:2014-05-22 18:44:11

标签: php mysql sql codeigniter

我想检查内部条件是另一个查询的结果。

英文+ sql这个where条件是这样的  where(table.field1 = $ data [field1],此$ data [field1]应仅来自另一个查询的结果。)

。我试过这个

if( isset($data['field1']) && $data['field1'] != '' ) {
                $this->db->where('table.field1',$data['field1'] IN (SELECT id FROM table2' WHERE id=2') );
            }

但这会导致错误

2 个答案:

答案 0 :(得分:1)

试着这样做

if( isset($data['field1']) && $data['field1'] != '' ) { 
   $this->db->where('table.field1',$data['field1']);
   $this->db->where('table.field1 in ','(SELECT id FROM table2 WHERE id=2)',false);
}

答案 1 :(得分:1)

public function get_category_with_all_sub() {
    $cquery = $this->db->get ( 'category' );
    $cresults = $cquery->result ();

    $return = array ();
    foreach ( $cresults as $c ) {
        $category_name = $c->name;
        $this->db->select ( '*' );
        $this->db->from ( 'sub_category' );
        $this->db->where ( 'category_id', $c->id );

        $squery = $this->db->get ();

        $sresults = $squery->result ();

        foreach ( $sresults as $s ) {
            $return [$category_name] [] = array (
                    'id' => $s->id,
                    'name' => $s->name,
                    'desc' => $s->description 
            );
        }
    }

    return $return;
}

请构建这样的模型函数,$c->id来自另一个结果。