2017-06-12 65 views
0

我有很多條件組合可能會進入數據庫調用,我不可能爲每個調用分別調用。我會有太多的if/else語句。phpactiverecord的一系列條件

,所以我想,而不是推的條件到一個數組動態生成兩個條件語句和傳遞價值觀 這樣:

$cond_values = array(); 
    $cond_values[] = $lender->id; 
    $cond_string = "lender_id = ?"; 

    if (something) { 
     $cond_string .= " AND search_id =?"; 
     $cond_values[] = $search_id; 
    } 
    if (something_else) { 
     $cond_string .= " AND cust_id =?"; 
     $cond_values[] = $cust_id; 
    } 

    $matches = Match::all(array(
     "select" => $select, 
     "conditions" => array($cond_string, $cond_values), 
     "order" => $order, 
     "joins" => $joins 
    )); 

但這僅僅在進行$ cond_values中有0或1個元素。不止一個值,我得到一個「沒有索引1的限制參數」錯誤。它似乎只會如果我這樣做:

$matches = Match::all(array(
     "select" => $select, 
     "conditions" => array($cond_string, $cond_values[0],$cond_values[1]), 
     "order" => $order, 
     "joins" => $joins 
    )); 

但值的數量會有所不同,所以我不能這樣做。我會很感激任何見解。

回答

1

試試這個:使用array_unshift()$cond_string推到開始你$cond_values數組,然後傳遞數組Match::all()

$cond_values = array(); 
$cond_values[] = $lender->id; 
$cond_string = "lender_id = ?"; 

if (something) { 
    $cond_string .= " AND search_id =?"; 
    $cond_values[] = $search_id; 
} 
if (something_else) { 
    $cond_string .= " AND cust_id =?"; 
    $cond_values[] = $cust_id; 
} 

array_unshift($cond_values, $cond_string); 

$matches = Match::all(array(
    "select" => $select, 
    "conditions" => $cond_values, 
    "order" => $order, 
    "joins" => $joins 
)); 
+0

完美!你是一個救星! – bjacobs