Yii selecting only specified attributes in array

Rajat Singhal picture Rajat Singhal · Jul 19, 2012 · Viewed 49.3k times · Source

I often face this problem..

Lets say ..In blog application, I need to email all the active users..

What I do is write findAll on users with some conditions of their last login being greater than some value..and get all the User objects...Then run a foreach through all the user model objects and store emails in a array, then use the array..

I other words what is happening in back-end is I am loading whole model, while I only need barely0.5% of that information, and then running a dirty code to get values in in array, and then process with it..

Isn't it quite bad in performance and dirty code..

Now other approach I can think of is using commandBuilder and write query and then run same dirty code to get values in array..one problem of performance resolved..but as people say writing sql in mvc frameworks, is not a really good idea..

What I really want...some similar functions which give me column values in array if it is a single column, or array with column name as index if multiple columns..

So what I am thinkin of doing is implement it by extending ActiveRecord or something similar, what I want to check is if some one has already implemented something similar, or have some ideas for it..:)

Answer

Onkar Janwa picture Onkar Janwa · Jul 20, 2012

You must study of CDbCriteria deeply, their is all the things what your looking.

Have an example::

$criteria = new CDbCriteria;
$criteria->select = 't.first_name, t.email'; // select fields which you want in output
$criteria->condition = 't.status = 1';

$data = Users::model()->findAll($criteria);

$data is also an array output.