繁体   English   中英

phpactiverecord的条件数组

[英]An array of conditions for phpactiverecord

我有很多条件组合,可能会进入db调用,因此我无法分别为每个调用。 我会有太多的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
    ));

但是值的数量会有所不同,所以我不能这样做。 我将不胜感激。

尝试以下操作:使用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
));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM