在cakephp 3.3中查询之间

时间:2017-03-31 11:56:47

标签: php mysql cakephp cakephp-3.0

查询正在运作

想使用cakephp 3.3

编写下面的查询
SELECT 

Books.id AS Books__id,   Books.title AS Books__title,   Books.for_min_age AS Books__for_min_age,   Books.for_max_age AS Books__for_max_age,   Books.for_min_grade AS Books__for_min_grade,   Books.for_max_grade AS Books__for_max_grade 从   书籍 哪里     4 BETWEEN Books.for_min_age AND Books.for_max_age     要么     2 BETWEEN Books.for_min_grade AND Books.for_max_grade

2 个答案:

答案 0 :(得分:0)

我想知道你是否试图找到答案。如果是这种情况,您会发现BETWEEN将无法按照您在此处描述的方式运行。 AFAIK。

以下代码适用于CakePHP,假设您的模型设置正确。

$age = 4;
$grade = 2;

$query = TableRegistry::get('Books')->find('all')
    ->select([
        'id', 
        'title',
        'for_min_age',
        'for_max_age',
        'for_min_grade',
        'for_max_grade'
    ]);

$query->where(function ($exp) use ($age, $grade) {
    $ageExp = $exp->and_(function ($and) use ($age) {
        return $and
            ->lte('for_min_age', $age)
            ->gte('for_max_age', $age);
    });

    $gradeExp = $exp->and_(function ($and) use ($grade) {
        return $and
            ->lte('for_min_grade', $grade)
            ->gte('for_max_grade', $grade);
    });

    return $exp->add(['OR' => [$ageExp, $gradeExp]]);
});

$data = $query->execute();

这将导致:

SELECT 
  Books.id AS `Books__id`, 
  Books.title AS `Books__title`, 
  Books. for_min_age AS `Books__for_min_age`,
  Books. for_max_age AS `Books__for_max_age`,
  Books. for_min_grade AS `Books__for_min_grade`,
  Books. for_max_grade AS `Books__for_max_grade` 
FROM 
  books Books 
WHERE 
  (
    (
      for_min_age <= 4 
      AND for_max_age >= 4
    ) 
    OR (
      for_min_grade <= 2 
      AND for_max_grade >= 2
    )
  )

修改

理论上你可以这样做,但是CakePHP会将numbernumber2作为字符串,这是行不通的。

$query->where(function ($exp) use ($age, $grade) {
    return $exp->or_(function ($or) use ($age) {
        return $or->between($age, 'for_min_age', 'for_max_age');
    })->between($grade, 'for_min_grade', 'for_max_grade');
});

答案 1 :(得分:0)

我通过 -

实现了这个目标
 $this->find()->where([$age . ' BETWEEN Books.for_min_age AND Books.for_max_age OR ' . $grade . ' BETWEEN Books.for_min_grade AND Books.for_max_grade']);