https://github.com/rajatsinghal/CAdvancedArFindBehavior
This extension is useful when you need array of values of a particular attribute based on some condition, and loading whole objects for them is not only big data pull and hence slow, but also it's more code, as you will have to traverse through all the objects and foreach of them put the required attrute's value in the array, and then proceed with it...
With this extension you have one function similar to findAll, in which one extra attribute column to select you need to provide, and it return array containing all row's values for that attribute.
This is a similar function to pluck of ruby on rails.
To use this extension, just copy this file to your extensions/ directory,
add 'import' => 'application.extensions.CAdvancedArFindBehavior', [...] to your config/main.php and
add this behavior to each model you would like to inherit the new possibilities:
public function behaviors(){ return array( 'CAdvancedArFindBehavior' => array( 'class' => 'application.extensions.CAdvancedArFindBehavior')); }
Syntex
public array findColumn(string $column, mixed $condition='', array $params=array()) {}
Things to Notice
beforeFind, afterFind functions also will be ignored. Scopes will work as normal. Example
$active_users_emails = User::model()->findColumn('email', 'active = 1');
returns array('rajat@gmail.com','rajatsinghal@gmail.com').. which is emails of all users who have active field as 1.
OR
$active_users_emails = User::model()->findColumn('email', array( 'condition'=>'active = :status_active', 'order'=>'join_date', 'limit'=>15, 'params'=>array('status_active'=>User::STATUS_ACTIVE) ));
Nice one!
I've been using this extension for a long time already and just felt the urge to say thanks. It's really weird Yii doesn't come with this option by default.
The only thing that's missing is another function that automatically executes a SELECT DISTINCT query that also selects the chosen attribute in ascending order. Of course this can be done via criteria but then you end up typing a lot of extra code, again.
class CAdvancedArFindBehavior extends CActiveRecordBehavior { public function findDistinct($column, $condition='', $params=array(), $distinct=true) { return self::findColumn($column, $condition, $params, $distinct=true); } public function findColumn($column, $condition='', $params=array(), $distinct=false) { $criteria = $this->owner->getCommandBuilder()->createCriteria($condition,$params); $criteria->select = $column; if($distinct==true) { $criteria->select = 'DISTINCT '.$column; $criteria->order = $column.' ASC'; } //... } }
Maybe there's a smarter way to accomplish this?
If you have any questions, please ask in the forum instead.
Signup or Login in order to comment.