yii - 使用 CDbCriteria 搜索

标签 yii

有没有办法在我选择的字段中进行 CDbCriteria 搜索(如 compare()),但使用模型的 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...
));

最佳答案

更新:您似乎是actually looking (来自此答案下面的评论)对于部分匹配,为此您必须将 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 instead :

$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

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

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

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

那么您甚至不需要addCondition,您可以简单地使用更复杂的条件 ( doc ) :

$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
);

关于yii - 使用 CDbCriteria 搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13047492/

相关文章:

php - 如何在 Yii 中获取当前的 Action id?

php - 如果在 Yii 中选中复选框,则弹出一个窗口

php - 使用 Yii session 进行负载均衡

php - fatal error : Call to a member function getDbCriteria() on a non-object

yii - 在 YII Framework 结构中的什么地方放置 "common"类?

php - yii 框架上的 ajax 响应非常慢

php - yii2中gridview中的数据更新问题

php - CArrayDataProvider 显示空值

twitter-bootstrap - 属性 "TbMenu.itemCssClass"未定义

html - 如何在 ClinkPaget yii 中的 <a></a> 之间添加标签 <span>