CakePHP 3查询结合IF / AND / OR

时间:2017-05-09 19:42:17

标签: php mysql cakephp cakephp-3.x

如何在CakePHP 3中实现此代码?

function notEmpty($field) {
    return isset($field) && $field != '';
}

$conditions[] = notEmpty($group_id) ? "group_id LIKE %$group_id%" : '';
$conditions[] = notEmpty($token) ? "firstname LIKE %$token% OR lastname LIKE %$token% OR username LIKE %$token%" : '';
$conditions[] = notEmpty($parent_id) ? "parent_id LIKE %$parent_id%" : '';
$conditions[] = notEmpty($status) ? "status1 LIKE %$status% AND status2 LIKE %$status%" : '';

$conditions = array_filter($conditions , function($value) { return $value !== ''; });//Remove empty conditions
array_walk($conditions, function(&$item) { $item = "($item)"; });//Add () to conditions
$where = !empty($conditions) ? 'WHERE '.implode(' AND ', $conditions) : '';
$query = 'SELECT * FROM users '.$where;

我正在使用分页。

1 个答案:

答案 0 :(得分:1)

这是非常简单的代码:)绝对不复杂。

最简单和最直接的答案是下面的代码(假设用户表):

$conditions = [];
if (!empty($group_id)) {
  $conditions['group_id LIKE'] = '%' . $group_id . '%';
}
if (!empty($token)) {
  $conditions['or'] = [
    'firstname LIKE' => '%' . $token . '%',
    'lastname LIKE' => '%' . $token . '%',
    'username LIKE' => '%' . $token . '%',
  ];
}
if (!empty($parent_id)) {
  $conditions['parent_id LIKE'] = '%' . $parent_id . '%';
}
if (!empty($status)) {
  $conditions['status1 LIKE'] = '%' . $status . '%';
  $conditions['status2 LIKE'] = '%' . $status . '%';
}
$query = $this->Users->find()->where($conditions);

然后,您可以轻松地将$query传递给控制器​​中的paginate()方法。

更好,更强大且可维护的解决方案是使用FriendsOfCake搜索插件https://github.com/friendsofcake/search