peymang
(Peymanpyq)
April 11, 2015, 4:13pm
1
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?
By any chance, are you looking for indexBy() ?
peymang
(Peymanpyq)
April 11, 2015, 7:56pm
3
thank you for replay
i want get records like this:
array (size=6)
1 => string ‘google’ (length=6)
2 => string ‘ubuntu’ (length=6)
4 => string ‘apple’ (length=5)
5 => string ‘adobe’ (length=5)
9 => string ‘microsoft’ (length=9)
if i want do this with php write:
$pdo = new PDO('mysql:host=localhost;dbname=db', 'root', '');
$sql = 'SELECT id,name FROM developer';
$q = $pdo->query($sql);
$q->setFetchMode(PDO::FETCH_KEY_PAIR);
$q->execute();
var_dump($q->fetchAll());
but i want do this with activerecord.
I know that I can use the array helper or write function to do this
but i want know is there an option to set this property($q->setFetchMode(PDO::FETCH_KEY_PAIR) ).
There probably is through \Yii::$app->db->pdo . I’d advise against it, though.
peymang
(Peymanpyq)
April 11, 2015, 9:13pm
5
i use
\yii::$app->db->pdo->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_KEY_PAIR);
and get this error:
Call to a member function setAttribute() on a non-object
can you give me a example by code?
Hm, I suspect the PDO object hasn’t been loaded at that point. You can try opening the connection up by calling [font=“Courier New”]\Yii::$app->db->open()[/font] first. Alternatively try setting that flag through the attributes in your db config.