我想在where where条件下传递多个id怎么做?
查询从数据库中提取org_id
。
现在我想在我的情况下通过那个,那该怎么做?
我试过foreach循环:
以下是代码:
$devices = $this->activation_m->get_activated_devices();
$org_id = array(); // create org_id array
foreach ($devices as $row)
{
$org_id[]= $row['org_id']; // assign ids into array
//$companys =$this->data['devices'] = $this->activation_m->get_company($org_id); // don't call again and again
}
//Now $org_id is array
$companys =$this->data['devices'] = $this->activation_m->get_company($org_id);
echo $this->db->last_query();
型号代码
public function get_activated_devices()
{
$this->db->select('*');
$this->db->join('sitekey','sitekey.site_key = activation.site_key');
$this->db->from('activation');
$query =$this->db->get();
$result = $query->result_array();
return $result;
}
public function get_company($org_id)
{
$this->db->select('*');
$this->db->join('sitekey','sitekey.org_id = company.id');
$this->db->join('activation','sitekey.site_key = activation.site_key');
$this->db->where('company.id IN',(implode(',',$org_id))); // see the change here
$this->db->from('company');
$query =$this->db->get();
$result = $query->result_array();
return $result;
}
现在我的查询目前只传递了一个org_id
,我想传递我从第一个查询中获得的所有org_id
。
答案 0 :(得分:3)
您可以使用来自活动记录codeigniter的where_in
as
$devices = $this->activation_m->get_activated_devices();
$org_id = array();
foreach ($devices as $row)
{
$org_id[] = $row['org_id'];
}
$companys =$this->data['devices'] = $this->activation_m->get_company($org_id);
if( $companys->num_rows() > 0 )
{
echo "<pre>";
print_r( $companys->result());
echo "</pre>";
}
对于模型
public function get_company($org_ids = array())
{
$this->db->select('*');
$this->db->join('sitekey','sitekey.org_id = company.id');
$this->db->join('activation','sitekey.site_key = activation.site_key');
$this->db->where_in('company.id', $org_ids ); //this is condition
$this->db->from('company');
return $this->db->get();
}
答案 1 :(得分:1)
您可以将codeigniter的$this->db->or_where()
用于此目的。只需遍历组织ID的数组并应用or_where条件。
$this->db->select('*');
$this->db->join('sitekey','sitekey.org_id = company.id');
$this->db->join('activation','sitekey.site_key = activation.site_key');
foreach($org_id as $org)
{ // where $org is the instance of one object of active record
$this->db->or_where('company.id',$org);
}
$this->db->from('company');
$query =$this->db->get();
$result = $query->result_array();
return $result;
另一种方法是通过像这样遍历数组并在字符串中附加where子句来创建自定义查询。