我有很多条件组合可能会进入数据库调用,我无法为每个调用单独调用。我的if / else语句太多了。
所以我想把条件推入一个数组来动态构建条件语句和传入的值。 所以:
$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
));
但价值量会有所不同,所以我无法做到这一点。我很欣赏任何见解。
答案 0 :(得分: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
));