3

I have table like this:

CREATE TABLE `developer` (
  `id` bigint(20) AUTO_INCREMENT,
  `name` varchar(1024) NOT NULL,
  `link` varchar(1024) NOT NULL,
  `parent` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `parent` (`parent`),
  CONSTRAINT `developer_ibfk_1` FOREIGN KEY (`parent`) REFERENCES `developer` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB CHARSET=utf8 COLLATE=utf8_unicode_ci;

I want get only id,name in PDO::FETCH_KEY_PAIR array from this table and use:

Developer::find()->select(['id', 'name'])->asArray()->all();

But I can not get the data in PDO::FETCH_KEY_PAIR format
how can i do it?

2 Answers 2

3

You may use ArrayHelper for generate array with key is id field and value is name field. Use like that:

ArrayHelper::map(Developer::find()->select(['id', 'name'])->asArray()->all(), 'id', 'name')

For more http://www.yiiframework.com/doc-2.0/guide-helper-array.html#building-maps

Edit: You may use createCommand, like that:

$res = Yii::$app->db->createCommand('SELECT id, name FROM developer')->queryAll(PDO::FETCH_KEY_PAIR);

But if you want use ActiveRecord see in https://github.com/yiisoft/yii2/blob/master/framework/db/Query.php#L204 In this line not set fetchMode.

You may take this class Query, ActiveRecord and change his. And extends your Develop model from new class.

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

1 Comment

i know it and this is not solution , maybe yii2 have another option to choose fetch method.
1

add code in controller

public function actionViewdata() {
    $model = new Contact();
    $data = $model::find()
            // ->where(['id' > 0])
            //->orderBy('age')
            ->all();
    return $this->render('viewdata', array(
                'model' => $model,
                'contactdata' => $data,
    ));
}

now in view(viewdata.php)

echo'<pre>';
print_r($contactdata);

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.