0

This code work fine:

$criteria = new CDbCriteria;
$criteria->compare('id', 1);
$dataProvider = new CActiveDataProvider('User', array('criteria'=>$criteria));
foreach ($dataProvider->getData() as $value) var_dump($value->id);

But when I change criteria after create CActiveDataProvider instance this does not work:

$criteria = new CDbCriteria;
$criteria->compare('id', 1);
$dataProvider = new CActiveDataProvider('User', array('criteria'=>$criteria));
$criteria->compare('id', 2);
foreach ($dataProvider->getData() as $value) var_dump($value->id);

This return empty! Why is this?

Nabi K.A.Z.
  • 9,887
  • 6
  • 59
  • 81
  • you are overwriting the criteria. – Sudhanshu Saxena Mar 21 '13 at 09:34
  • not overwriting, just adding a compare condition, your final condition is something like this : `id='1' AND id='2'`... – soju Mar 21 '13 at 09:42
  • But I change criteria after create instance of CActiveDataProvider ! – Nabi K.A.Z. Mar 21 '13 at 09:47
  • 2
    You should learn about references : http://php.net/manual/en/language.oop5.references.php – soju Mar 21 '13 at 09:50
  • @soju, Very thanks, If you post this comment via new answer, sure I check mark it for best answer ;) really my question was 'How use of one criteria for a CActiveDataProvider and then change some methods from same criteria and use it for another new instance of CActiveDataProvider.' I read that article and find solution: $criteria2 = clone $criteria; $criteria2->compare('id', 2); – Nabi K.A.Z. Mar 21 '13 at 11:54
  • We couldn't guess this, you should have been more explicit :) – soju Mar 21 '13 at 13:00

1 Answers1

3

You don't have any result since you are adding a condition to your criteria : generated SQL will look like this : WHERE id='1' AND id='2'

If you want to list user 1 and 2 you should try :

$criteria->compare('id', 2, false, 'OR');

Or simply use addInCondition.

EDIT : as you said in your comment, instead of using the same criteria object, you can clone it.

soju
  • 25,111
  • 3
  • 68
  • 70
  • I think the `addInCondition` would be better: Instead of doing `$criteria->compare('id', 1);` `$criteria->compare('id', 2, false, 'OR');` you'll simply do `$criteria->addInCondition('id', array(1,2));` – darkheir Mar 21 '13 at 09:50
  • but I don't have problem with work with criteria! I want use of one criteria for a CActiveDataProvider and then change some methods from same criteria and use it for another new instance of CActiveDataProvider. – Nabi K.A.Z. Mar 21 '13 at 11:36