Hi,
till today i was using this type of expressions when needed:
$arr = CHtml::listData(MyModel::model()->findAll(), 'id', 'id');
which basically gives me an array with ids needed (maybe with conditions). After that i used that array to build JSON responses or sometimes to run another database search like this:
AnotherModel::model()->findAllByAttributes(array('parent_id'=>$arr));
Today i’ve found it is incorrect. If suddenly first expression (CHtml::listData(…)) return an array with just 1 value, i.e. array(2=>2), then second expression will run a weird SQL query instead of … IN … condition it will create WHERE parent_id
IS NULL… What?! Ok, i go to sources and find out that class CDbCommandBuilder contains a method createInCondition which has following code at line 663:
return $prefix.$column->rawName.($values[0]===null?' IS NULL':'='.$values[0]);
This means that when an array, that i provide to findAllByAttributes as values, consists of just 1 value and has an index key NOT 0, i will get that weird WHERE condition.
Now, i thought it’s a bug and before petitioning it i searched for a while and found this: http://code.google.com/p/yii/issues/detail?id=2189
Basically Qiang says it’s not a bug, but bad usage of createInCondition method. Wow. So, my question is how do you do it right? How should i convert a collection of models MyModel::model()->findAll() into an array of values (not all fields, but just one) to pass it to AR?