php - phpactiverecord 的条件数组

标签 php mysql codeigniter activerecord 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 个元素时有效。超过一个值时,我收到“索引 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/

相关文章:

php - 当添加到列表的对象相同时,是否可以避免在 php 中重复调用方法?

php - 如何在 PHP 中实现回调?

mysql - 从 MySQL 表中选择数据

php - 调用 CI 4 中未定义的函数 form_open()

php - 我们可以在Codeigniter中定义常量数组吗?

javascript - PHP Mysql Insert Into 不工作,没有数据发布到数据库时没有错误,早些时候同一页面正在工作

php - 具有多个字值的选项标签

php - MySql 检查数字

php - 具有 N :M relationship (including relationship) 的重复表

jquery - 让 Uploadify 与 Codeigniter 一起使用?