How to make criteria with complex query in Yii framework?

php, yii

Solution

You could still build this statement with a CDbCriteria I think... something like:

$criteria=new CDbCriteria;
$criteria->condition = '
  (
    (
      userId = 1 OR 
      userId IN (SELECT userId FROM follower WHERE followerId = 1)
    )
    AND activityType IN(1, 2, 3)
  )
  OR (
    targetId = 24 
    AND aType IN(1, 2, 3, 4, 5)
  )
';
$criteria->order = 'id DESC';
$results=Activity::model()->findAll($criteria);

As this point you might as well just write a regular SQL statement, but there might be some benefits to doing it this way: binding params, merging criteria, adding additional criteria, etc.

Problem

I have query like this: ``` SELECT * FROM activity WHERE (((userId = 1 OR userId IN(SELECT userId FROM follower WHERE followerId = 1)) AND activityType IN(1, 2, 3)) OR (targetId = 24 AND aType IN(1, 2, 3, 4, 5))) ORDER BY id DESC; ``` I have try to use `model()->findAllBySql($sql)` and it works. But I want to make it using `CDbCriteria`, if you have another solutions let me know it :D

Original source