2013-10-07 72 views
0

我有一個模型/數據庫表看起來像這樣Yii的PHP的:獲得具有關聯數組特定鍵值

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

從數據庫中檢索模型之後:

說:

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

,並想我也檢索到的10行..匹配的groupId給出

我想存儲匹配的10行的所有first_name。

我知道這可以這樣做:

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

但有另一種方式,例如一個PHP功能,做同樣的事情?謝謝!

回答

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'); 

了CHtml ::的ListData()與像返回一個關聯數組:[ 'ID'] => '如first_name'(模型的屬性)

0

你可以先算模型符合GROUP_ID,如:

PersonModel ::模型() - > countByAttributes(陣列( 'GROUP_ID'=> $的groupId));

然後你可以將它限制爲10並命令它desc並獲得匹配的最新10行!

Yii : how to count records in a model?

相關問題