CakePHP 3 查询组合 IF/AND/OR

CakePHP 3 query combining IF/AND/OR

如何在 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;

我正在使用分页。

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

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

$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