Select the record ids in Yii [closed]
I have a table and i need to pull all the ids (all the primary keys) corresponding a certain pattern. I need this to be done with the model class in Yii and save them to an array for further processing.
Here is one way to do what it seems like you are asking. In this example the model is "People" and the pattern is job_title LIKE "%developer%"
-- post-processing is done to put into an array. If you can use an object, skip the post processing.
$criteria=new CDbCriteria;
$criteria->select = 'people_id';
$criteria->condition='job_title LIKE :txt';
$criteria->params=array(':txt'=>'%developer%');
$people=People::model()->findAll($criteria);
// save to array:
$people_a = array();
foreach ($people as $person) {
$people_a[] = $person['people_id'];
}
A slightly more efficient way to do it (if you need the result to be an array) that allows you to use CommandBuilder and your existing models is:
$model = People::model();
$model->dbCriteria->condition .= 'job_title LIKE :txt';
$model->dbCriteria->select = 'people_id';
$model->dbCriteria->params = array(':txt'=>'%developer%');
$people = $model->getCommandBuilder()
->createFindCommand($model->tableSchema, $model->dbCriteria)
->queryAll();
$people_a = array();
array_walk($people, function ($value) use (& $people_a) {
$people_a[] = $value['people_id'];
});
(the anonymous function above assumes PHP 5.3)
There is no way to select only IDs with ActiveRecord pattern. You can use CCommandBuilder to build sql query.
精彩评论