2

有没有办法在compare()我选择的字段中进行 CDbCriteria 搜索(如 ),但使用模型的search()方法而不是手动添加compare()条件?

请注意,我的目标是让我写更少的行,不多也不少。所以,如果解决方案真的很麻烦和/或混乱,我会选择“add-a-few-compares()”方法。

我当前的代码:

$criteria = new CDbCriteria;
$criteria->with = array('A', 'B', 'C', 'D', 'E');

$criteria->compare("A.field1", "test", false, 'OR');
$criteria->compare("A.field2", "test", false, 'OR');
$criteria->compare("B.field1", "test", false, 'OR');
$criteria->compare("B.field2", "test", false, 'OR');

$dataProvider = new CActiveDataProvider('Z', array(
    'criteria'=>$criteria,
    //pagination...
    //more options...
));
4

1 回答 1

2

更新:您似乎实际上正在寻找(来自此答案下方的评论)部分匹配,为此您必须传递true给您的compare电话:

$criteria->compare("A.field1", "test", true, 'OR');

甚至可以传递给addCondition

$criteria->addCondition('A.field1 LIKE "%test"','OR');
// or with params as below
$criteria->addCondition('A.field2 LIKE :test','OR');
$criteria->params=array(
    ':test'=>'%test%',
);

正如我在评论中已经提到的,我认为不可能使用每个模型的默认search()方法。但是还有其他选择,例如您可以addCondition使用

$criteria = new CDbCriteria;
$criteria->with = array('A', 'B', 'C', 'D', 'E');
$criteria->together = true; // you'll need together so that the other tables are joined in the same query

$criteria->addCondition('A.field1 = "test"','OR');
$criteria->addCondition('A.field2 = "test"','OR');
// and so on

我建议使用上述内容,因为compare (doc-link)实际上应该用于您想要“智能”确定比较运算符的情况,例如:如果您从用户输入中获取测试值并且用户是允许使用运算符(<、>、<= 等)。在确定了要在条件中使用的运算符后,相应地compare调用其他函数,包括addCondition. 所以使用addCondition至少会避免那些不必要的检查。

此外,如果您所要做的只是检查相等性,即如果您的 sqlWHERE应该是:

WHERE A.field1 = "test" OR A.field2 = "test"

那么你甚至不需要addCondition,你可以简单地使用更复杂的conditiondoc):

$criteria->condition='A.field1 = "test" OR A.field2 = "test"';
// or even better if you use params
$criteria->condition='A.field1 =:test1 OR A.field2 =:test2 OR B.field1 =:test3 OR B.field2 =:test3';
$criteria->params=array(
    ':test1'=>'test',
    ':test2'=>'anothertest',
    'test3'=>'tests' // omitting ':' here for params also works
);
于 2012-10-24T14:09:08.520 回答