What do people think of the idea of adding the option to return an associative array, indexed by one of the fields of the data (generally a unique field), instead of a plain numerically indexed array for findAll and *_MANY relationships? I’m not sure if it’s common to structure data sets like this… I find it useful to index by Primary Key, particularly when a lot of different related sets of data are being used. I’m unsure of the performance compares, using an associative array versus performing a foreach every time it is required, or performing an extra database lookup using a relation.
The conversion is trivial, I know, but given that the entire result set is being looped through anyway to create the array in the first place I thought the core might be a good place to add it.
I still like this idea and find this feature very useful for different cases. Actually this already was requested several times but never implemented. I think there where concerns that it breaks some functionality (was it CDataProvider…? Can’t remember.) Another concern was, that the chosen attribute might not be unique.
In my opinion, the developer will know, in which situation to use this and when not.
We could have a index property in CDbCriteria, that defaults to null. If set to an attribute name, this attribute is used to index the resultset.
Here an example what this is useful for. Think of a small tree, stored in DB with parent/child relations. If i want to read in the complete tree and access every node and its children, i could now do this:
$categories=Category::model()->findAll(array('index'=>'id'));
foreach($categories as $id => $category)
$categories[$category->parent_id]->children[$id] = $category;
Now i have a nice representation of the complete tree. Each node is accessible by its id. And each node has an array of its children.
If i want to do that now, i need another loop first to convert the zero based array into an id-indexed one.