2013-04-18 96 views
2

我正在尋找一種在CodeIgniter中使用Active Record構建查詢的方法。使用CodeIgniter Active Record語句

我當前的代碼是這樣的:

$this->db-> like('responsible', $user->id); 
$this->db->or_like('accountable', $user->id); 
$this->db->or_like('consulted', $user->id); 
$this->db->or_like('informed', $user->id); 

// Get the tasks, but only with the correct start or end date 
$tasks = $this->db->get_where('level_' . $this->config->item('answer_level'), array('date_end' => $offset, 'ccode' => $user->country)); 

// Check if tasks exist 
if($tasks->num_rows() > 0){ 
    // Tasks have been found that should have been finished! 
    echo $tasks->num_rows() . " tasks found for " . $user->first_name . " that should have been finished!\n"; 
    $last_month_tasks = $tasks->result(); 
} 

unset($tasks); 

將會產生如下SQL:

SELECT * 
FROM (`level_3`) 
WHERE `date_start` = -5 
AND `ccode` = 'GB' 
AND `responsible` LIKE '%5%' 
OR `accountable` LIKE '%5%' 
OR `consulted` LIKE '%5%' 
OR `informed` LIKE '%5%' 

但我需要它來製作這個SQL:

SELECT * 
FROM (`level_3`) 
WHERE `date_start` = -5 
AND `ccode` = 'GB' 
AND (
`responsible` LIKE '%5%' 
    OR `accountable` LIKE '%5%' 
    OR `consulted` LIKE '%5%' 
    OR `informed` LIKE '%5%' 
) 

回答

3

CodeIgniter的ActiveRecord的不支持查詢和子句的嵌套。 你必須這樣做:

$this->db->select('*'); 
$this->db->from('level_' . $this->config->item('answer_level')); 
$this->db->where(array('date_end' => $offset, 'ccode' => $user->country)); 
$this->db->where("(responsible LIKE '%5%' OR accountable LIKE '%5%' OR consulted LIKE '%5%' OR informed LIKE '%5%')"); 
$tasks = $this->db->get(); 
+0

謝謝,我要編輯SQL來修復你的答案中的一些東西。 – Adam

相關問題