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?
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With