Yii - 通过LIKE条件了解运算符以通过CDBCriteria构建SQL

时间:2013-02-11 15:34:29

标签: yii

这是我想通过Yii CDBCriteria实现的SQL:

WHERE 
    (
        (field1 LIKE '%value1%') AND (field1 LIKE '%value2%')
    ) OR (
        (field2 LIKE '%value1%') AND (field2 LIKE '%value2%')
    ) OR (
        (field3 LIKE '%value1%') AND (field3 LIKE '%value2%')
    )

如果字符串以任何顺序包含“value1”或“value2”,则返回该行。例如:

  

Lorem value1 ipsum value2 sir dolor amet。

OR

  

Lorem value2 ipsum value1 sir dolor amet。

但如果只有一个值,则不会返回任何内容。

我尝试过的(来自this thread):

$c = new CDbCriteria;
$c->addColumnCondition(array('field1 LIKE' => '%value1%', 'field1 LIKE' => '%value2%'), 'AND', 'OR');
$c->addColumnCondition(array('field2 LIKE' => '%value1%', 'field2 LIKE' => '%value2%'), 'AND', 'OR');
$c->addColumnCondition(array('field3 LIKE' => '%value1%', 'field3 LIKE' => '%value2%'), 'AND', 'OR');

但这不是如何在LIKE条件下使用它并且它只返回第二个比较,因为同一个字段的键是相同的:

(
    (field1 LIKE='%value2%') OR (field2 LIKE='%value2%')
) OR (field3 LIKE='%value2%')

所以我尝试过比较条件:

$c->compare('field1', 'value1', true);
$c->compare('field1', 'value2', true, 'OR');
$c->compare('field2', 'value1', true, 'AND');
$c->compare('field2', 'value2', true, 'OR');
$c->compare('field3', 'value1', true, 'AND');
$c->compare('field3', 'value2', true, 'OR');

OR

$c->addSearchCondition('field1', 'value1', false);
$c->addSearchCondition('field1', 'value2', false, 'OR');
$c->addSearchCondition('field2', 'value1', false);
$c->addSearchCondition('field2', 'value2', false, 'OR');
$c->addSearchCondition('field3', 'value1', false);
$c->addSearchCondition('field3', 'value2', false, 'OR');

但是我无法解决这个问题。这是我得到的:

(
    (
        (
            (
                (field1 LIKE '%value1%') OR (field1 LIKE '%value2%')
            ) 
            AND (field2 LIKE '%value1%')
        ) 
        OR (field2 LIKE '%value2%')
    ) 
    AND (field3 LIKE '%value1%')
) OR (field3 LIKE '%value2%')

所以,如果有人知道如何实现这一点,请帮助我:)

1 个答案:

答案 0 :(得分:6)

这是你在找什么?

$c->addCondition("field1 like :value1 and field1 like :value2", "OR");
$c->addCondition("field2 like :value1 and field2 like :value2", "OR");
$c->addCondition("field3 like :value1 and field3 like :value2", "OR");
$c->params = array(':value1' => '%'. $value1 .'%', ':value2' => '%'. $value2 .'%');

替代:

$c2 = new CDbCriteria;
$c2->addSearchCondition("field2", ':value1');
$c2->addSearchCondition("field2", ':value2');

$c3 = new CDbCriteria;
$c3->addSearchCondition("field3", ':value1');
$c3->addSearchCondition("field3", ':value2');

$c->addSearchCondition("field1", ':value1');
$c->addSearchCondition("field1", ':value2');
$c->mergeWith($c2, false);
$c->mergeWith($c3, false);