我想知道是否有可能从codeigniter活动记录合并如下sql查询。
//get assigned contacts
$this->db->select('*, CONCAT(first_name, " " ,last_name) AS name', FALSE);
$this->db->from('customers_contacts');
$this->db->join('customers_accounts', 'customers_accounts.contact_id = customers_contacts.contact_id');
$this->db->like('CONCAT(first_name, " " ,last_name)', $q);
$results1 = $this->db->get();
//get non assigned contacts
$this->db->select('*, CONCAT(first_name, " " ,last_name) AS name', FALSE);
$this->db->from('customers_contacts');
$this->db->like('CONCAT(first_name, " " ,last_name)', $q);
$results2 = $this->db->get();
我尝试使用$query = array_merge($results1, $results2);
,但这不起作用,我相信因为->get()
返回一个对象数组。
所以我让它通过一个foreach循环,然后合并结果数组来工作。但是我需要做一些条件,在一个foreach循环中比在两个foreach循环中更容易。
你可以在
下面使用like$arr_results1 = $this->db->get()->result_array();
$arr_results2 = $this->db->get()->result_array();
var_dump(array_merge($arr_results1,$arr_results2));
希望这对你有帮助!
经过一番阅读,我想出了以下方法,它很有效!
//first query here...
$results1 = $this->db->get()->result_array();
//second query here...
$results1 = $this->db->get()->result_array();
//then...
$query = array_merge($results1,$results2);
您必须始终执行$results->result();
以获得$results = $this->db->get();
之后的行数组。注意: $results->result();
是一个对象数组。
# ...
$results1 = $this->db->get();
# ...
$results2 = $this->db->get();
$results = array();
if ($results1->num_rows())
{
$results = array_merge($results, $results1->result());
}
if ($results2->num_rows())
{
$results = array_merge($results, $results2->result());
}
return $results;
这将返回一个对象数组(行),你像往常一样迭代数据:
foreach ($results as $row)
{
echo $row->id;
echo $row->column_name_1;
# and so on...
}