在Codeigniter Active Record中,在它们之间的两个相应元素和OR之间使用AND

时间:2016-04-21 08:02:04

标签: php codeigniter

请原谅我,如果我愚蠢,连续编码30个小时

需要最终输出:

  

SELECT * FROM cities_extended WHERE(state_code ='MO'AND   county ='GREENE')或(state_code ='NY'和county ='GREENE')

我的尝试: 我有这个查询(为测试而编写),我在codeigniter中为它编写了代码,但是我没能将它正确地转换为codeigniter的Active Record。我知道codeigniter的where_in和or_where_in函数。我尝试了以下代码:

// some code 
$counties = $query->result_array();
for($i = 0; $i < count($counties); $i++)
{
   $this->db->or_where('county', $counties[$i]['county']);
   $this->db->where('state_code', $counties[$i]['state_code']);
}
   $this->db->select('zip');
   $zips_query = $this->db->get('cities_extended');
   return $this->db->last_query();
 // some code

这给出了以下输出:

"SELECT `zip` FROM `cities_extended` WHERE `county` = 'Laclede' AND `state_code` = 'MO' OR `county` = 'Greene' AND `state_code` = 'MO' OR `county` = 'Webster' AND `state_code` = 'MO'"

Crux:我如何投入(县='帮助' state_code ='我')(县='WILL'使用 Codeigniter的有效记录 AND state_code ='YOU'。

3 个答案:

答案 0 :(得分:1)

你可以在下面的代码

中做
$this -> db -> select('*') -> from ('cities_extended') -> where("(state_code = 'MO' AND county= 'GREENE')") -> or_where("(state_code = 'NY' AND county = 'GREENE')");

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

编辑:请执行以下操作

for($i = 0; $i < count($counties); $i++)
{
   $this->db->or_where("'county' = '".$counties[$i]['county']."' AND 'state_code' = '".$counties[$i]['state_code."']");
}

答案 1 :(得分:0)

这样做了吗?我从阿伦的回答中得到了暗示。仍然需要改变一点。我按如下方式更改了循环体:

for($i = 0; $i < count($counties); $i++)
    $this->db->or_where("( state_code = '".$counties[$i]['state_code']. "' AND county = '".$counties[$i]['county']."' )");

答案 2 :(得分:0)

$this->db->select('*');
$this->db->from('cities_extended');
$this->db->where("state_code",  'MO');
$this->db->where('county','GREENE') 
$this->db->or_where("state_code",'NY');
$result = $this->db->get();