Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii selecting only specified attributes in array

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..:)

like image 706
Rajat Singhal Avatar asked Jul 19 '12 17:07

Rajat Singhal


Video Answer


2 Answers

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.

like image 102
Onkar Janwa Avatar answered Oct 06 '22 00:10

Onkar Janwa


In Yii2, you can use like this:

User::find()->select(['field1', 'field2']);
like image 22
Zhang Buzz Avatar answered Oct 06 '22 01:10

Zhang Buzz