phpactiverecord 条件数组
An array of conditions for phpactiverecord
我有太多可能进入数据库调用的条件组合,我不可能为每个条件单独调用。我有太多的 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 个元素时才有效。超过一个值,我得到一个 "No bound parameter for index 1" 错误。似乎只有我这样做才会有效:
$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
));
我有太多可能进入数据库调用的条件组合,我不可能为每个条件单独调用。我有太多的 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 个元素时才有效。超过一个值,我得到一个 "No bound parameter for index 1" 错误。似乎只有我这样做才会有效:
$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
));