Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

yii2 - fetch data with activerecord in FETCH_KEY_PAIR array format

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?

like image 360
Death Programmer Avatar asked Dec 08 '25 19:12

Death Programmer


2 Answers

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.

like image 172
vitalik_74 Avatar answered Dec 11 '25 16:12

vitalik_74


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);
like image 35
Ashish Pathak Avatar answered Dec 11 '25 14:12

Ashish Pathak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!