join和orwhere以AND结尾

时间:2015-06-09 15:42:20

标签: orm cakephp-3.0

我有以下代码:

$_duplicates = $this->find()
    ->innerJoin(
        ['c' => 'contacts'],    //alias
        [
            'Contacts.contactname != ' => '',
            'Contacts.id < c.id',
            'c.id > ' => 0
        ]
        )
    ->select(['Contacts.id', 'Contacts.contactname', 'Contacts.legalname',
              'c.id', 'c.contactname', 'c.legalname'])
    ->orWhere([
        'LEVENSHTEIN(Contacts.contactname, c.contactname) <= ' => $distance,
        'LEVENSHTEIN(Contacts.contactname, c.legalname) <= ' => $distance,
        'LEVENSHTEIN(Contacts.legalname, c.contactname) <= ' => $distance,
        'LEVENSHTEIN(Contacts.legalname, c.legalname) <= ' => $distance
        ]);
debug($_duplicates);

那里的调试给出了这个输出:

SELECT Contacts.id AS `Contacts__id`, Contacts.contactname AS `Contacts__contactname`, 
  Contacts.legalname AS `Contacts__legalname`, c.id AS `c__id`,
  c.contactname AS `c__contactname`, c.legalname AS `c__legalname` 
FROM contacts Contacts 
INNER JOIN contacts c 
ON (Contacts.contactname != :c0 AND Contacts.id < c.id AND c.id > :c1)   
WHERE (
   Contacts.active = :c2 
   AND (
      LEVENSHTEIN(Contacts.contactname, c.contactname) <= :c3 
      AND LEVENSHTEIN(Contacts.contactname, c.legalname) <= :c4 
      AND LEVENSHTEIN(Contacts.legalname, c.contactname) <= :c5 
      AND LEVENSHTEIN(Contacts.legalname, c.legalname) <= :c6
    )
  )

为什么我在LEVENSHTEIN电话而不是OR时获得AND-s?或者应该在那里创建OR关系,对吧?

1 个答案:

答案 0 :(得分:1)

因为orWhere()不应该如何工作,OR条件用于与先前通过where/andWhere/orWhere()定义的条件相结合,即< / p>

->where(['a' => 'b'])
->orWhere(['c' => 'd', 'e' => 'f'])

结果

(c = d AND e = f) OR a = b

如果您需要通过OR合并所有条件,那么您可以使用多个orWhere()来电

->orWhere(['a' => 'b'])
->orWhere(['c' => 'd'])
->orWhere(['e' => 'f'])

OR密钥

->where([
    'OR' => [
        'a' => 'b'
        'c' => 'd'
        'e' => 'f'
    ]
])

或表达式

->where(function (\Cake\Database\Expression\QueryExpression $exp) {
    return
        $exp->or_([
            'a' => 'b'
            'c' => 'd'
            'e' => 'f'
        ]);
})

另请参阅 Cookbook > Database Access & ORM > Query Builder > Advanced Conditions