2010-07-29 66 views
2

條件數組要獲得DB結果的條件如何連接CakePHP中

if($keyword!='') 
    build condition; 
    /* 
    array('conditions' => array("AND" => array ("esl.esl_artistname LIKE"=>"%".$artistname."%", 
    "esl.esl_songname LIKE"=>"%".$songname."%")), 
    'limit' => $arrFind['limit'], 
    'page'=>$arrFind['page'])); 
    */ 


if(!name!='') 
    /* 
    array('conditions' => array("esl.esl_artistname LIKE"=>"%".$artistname."%"), 
    'limit' => $arrFind['limit'], 
    'page'=>$arrFind['page'])) 
    */ 

$this->find('all',condition); 

基礎上如何做到這一點?如何連接兩個條件?

回答

5

爲什麼不初始化conditions數組,然後追加到它呢?

$conditions = array(); 
if(keyword != '') { 
    array_push(
    'conditions' 
    , array("AND" => array ("esl.esl_artistname LIKE"=>"%".$artistname."%", "esl.esl_songname LIKE"=>"%".$songname."%")) 
} 

if(!name != '') { 
    array_push('conditions', array("esl.esl_artistname LIKE"=>"%".$artistname."%") 
} 

$this->find('all', array('conditions' => $conditions, 'limit' => $arrFind['limit'], 'page' => $arrFind['page']; 
1

串聯條件可在下列方式進行:

$condition1 = array('Model1.field1 LIKE'=>'%'.$value.'%', 'Model1.field2'=>2); 
$condition2 = array('Model2.field2 LIKE'=>'%'.$value.'%', 'Model2.field2'=>1); 

$this->MyModel->find('all', array('conditions'=>am($condition1, $condition2))); 

上午是蛋糕的快捷方式array_merge。

4

我會做類似羅布·威爾克森建議,但這樣的:

$conditions = array(); 
if(keyword != '') { 
    $conditions[] = array("AND" => array ("esl.esl_artistname LIKE"=>"%".$artistname."%", "esl.esl_songname LIKE"=>"%".$songname."%")); 
} 

if(!name != '') { 
    $conditions[] = array("esl.esl_artistname LIKE"=>"%".$artistname."%"); 
} 

$this->find('all', array('conditions' => $conditions, 'limit' => $arrFind['limit'], 'page' => $arrFind['page'];