For example, let\'s use some simple data set
+---------+------+------+------------+
| name | age | sex | position |
+---------+------+------+---------
It doesn't look like anyone has mentioned this variation, so, for the benefit of future Googlers:
Combine the \PDO::FETCH_GROUP
and \PDO::FETCH_COLUMN
flags. This vastly simplified my SQL statement and returned the exact result set I wanted. It's fast, too.
$this->database->query('SELECT t.fk, t.id FROM my_table t ORDER BY t.fk ASC, t.id ASC')
->fetchAll(\PDO::FETCH_GROUP|\PDO::FETCH_COLUMN);
Where t.fk
has a one-to-many relationship with t.id
.
I didn't have to concern myself with a GROUP BY
statement or MySQL's finicky handling of grouping on multiple fields. Best of all, I received results in the form of:
[
foreign_key_1 => [
0 => 11111,
1 => 22222,
2 => 33333,
],
foreign_key_2 => [
0 => 44444,
1 => 55555,
2 => 66666,
],
foreign_key_3 => [
0 => 77777,
1 => 88888,
2 => 99999,
],
];
Rather than:
[
foreign_key_1 => [
0 => [
id => 11111,
],
1 => [
id => 22222,
],
2 => [
id => 33333,
],
],
foreign_key_2 => [
0 => [
id => 44444,
],
1 => [
id => 55555,
],
2 => [
id => 66666,
],
],
foreign_key_3 => [
0 => [
id => 77777,
],
1 => [
id => 88888,
],
2 => [
id => 99999,
],
],
];
Hope it helps someone out there!
For reference: https://phpdelusions.net/pdo/fetch_modes
Key assoc array
PDO::FETCH_GROUP|PDO::FETCH_UNIQUE|PDO::FETCH_ASSOC