For many-to-many relations, there is CHasManyRelation::$index, which lets you define which column-value becomes the key in the returned array.
How come there is no equivalent feature for models in general?
Currently, I have to override CActiveRecord::findAll() for every model an re-index the returned results…
Here’s what my extension method looks like:
class GActiveRecord extends CActiveRecord
* @param mixed $index attribute name for array index - or true, to indexed the returned array by primary key
* @see CActiveRecord::findAll()
public function findAll($condition='', $params=array(), $index=null)
$index = isset($this->indexBy) ? $this->indexBy : false;
return parent::findAll($condition, $params);
$index = $this->getTableSchema()->primaryKey;
$models = array();
foreach (parent::findAll($condition, $params) as $model)
$models[$model->$index] = $model;
Now, if the model declares a public $indexBy with the attribute name, the models will be reindexed before they’re returned.
Setting $indexBy to true will re-index by primary key - setting it to an attribute-name will re-index by that attribute.
So you define the convention in your model, but you can override it with the $index parameter in the method, which defaults to null, meaning use the model convention - setting it to false means don’t re-index.