开发者

Select the record ids in Yii [closed]

It's difficult to tell what is being asked her开发者_Python百科e. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 10 years ago.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜