如何使用yii框架查询具有多个条件的记录

时间:2016-06-14 09:07:05

标签: mysql yii

我希望所有结果都满足(age = 20,name = jim)或(age = 30,name = allen)或(age = 40,name = sam),如何用yii编写查询代码?

2 个答案:

答案 0 :(得分:2)

如果你使用yii 1:

$criteria = new CdbCriteria();
$criteria->addCondition('age = :age1 AND name = :name1', 'OR');
$criteria->addCondition('age = :age2 AND name = :name2', 'OR');
$criteria->addCondition('age = :age3 AND name = :name3', 'OR');
$criteria->params = [
    ':age1' => 20,
    ':age2' => 30,
    ':age3' => 40,
    ':name1' => 'jim',
    ':name2' => 'allen',
    ':name3' => 'sam',
];
$result = YourModelName::model()->findAll($criteria);

答案 1 :(得分:1)

如果您使用yii2

$query->orWhere(['AND',
                  ['age' => 20],
                  ['name' => 'jim']
                ])
      ->orWhere(['AND',
                  ['age' => 30],
                  ['name' => 'allen']
                ])
      ->orWhere(['AND',
                  ['age' => 40],
                  ['name' => 'sam']
                ])
     ->all();