【问题标题】:An array of conditions for phpactiverecordphpactiverecord的条件数组
【发布时间】:2017-06-12 17:12:48
【问题描述】:

我有太多可能进入数据库调用的条件组合,我不可能为每个条件单独调用。我会有太多的 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
    ));

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

【问题讨论】:

    标签: php mysql codeigniter activerecord phpactiverecord


    【解决方案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
    ));
    

    【讨论】:

    • 完美!你是救生员!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多