我有很多可能进入数据库调用的条件组合,因此我不可能对每个条件进行单独的调用。我有太多的 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 没有绑定(bind)参数”错误。看来只有我这样做才有效:
$matches = Match::all(array(
"select" => $select,
"conditions" => array($cond_string, $cond_values[0],$cond_values[1] ),
"order" => $order,
"joins" => $joins
));
但是值的数量会有所不同,所以我无法这样做。如果有任何见解,我将不胜感激。
最佳答案
试试这个:使用 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
));
关于php - phpactiverecord 的条件数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44505129/