0

I have a model/database table that looks like this

id | group_id| first_name | middle_name | last_name
------------------------------------------------------ 
   |          |            |             |      
------------------------------------------------------

After retrieving a model from the database:

say:

$people = PersonModel::model()->findAllByAttributes(array('group_id'=>$groupId));

and suppose i've retrieved 10 rows.. matching the groupId given

I want to store all the first_name of the 10 rows that matched.

I know this can be done by:

$personArray = array();
foreach($people as $person){
   $personArray[] = $person->first_name;
}

but is there another way, e.g. a php function that does the same thing? Thank you!

2 Answers 2

3
$criteria = new CDbCriteria;
$criteria->compare('group_id', $groupId);
$criteria->limit = 10;
$people = PersonModel::model()->findAll($criteria);
$personArray = $list = CHtml::listData($people, 'id','first_name');

The CHtml::listData() returns an associative array with like: ['id'] => 'first_name' (attributes of the model)

Sign up to request clarification or add additional context in comments.

Comments

0

you can first count the models matching your group_id, like:

PersonModel::model()->countByAttributes(array('group_id'=>$groupId));

then you can limit it to 10 and order it desc and get the latest 10 rows that matched!

Yii : how to count records in a model?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.