0

I want to get all the results satisfy (age=20, name=jim) or (age=30, name=allen) or (age=40, name=sam), how to write the query code with yii?

2
  • call $query->orWhere('age' => xx, 'name' => yy) in a foreach block, it works but not graceful enough Commented Jun 14, 2016 at 10:10
  • It's yii2 or yii1 ? Commented Jun 14, 2016 at 10:49

2 Answers 2

2

if you use 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);
Sign up to request clarification or add additional context in comments.

1 Comment

what if I add a constrain sex=male
1

If you use yii2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.