0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Cakephp4でfetchAll(PDO::FETCH_ASSOC)を使いたい

Posted at

何故必要か

ORMや、デフォルトでのConnectionManagerではfetchAll('assoc')やnumなど簡単なものしか使えず、取得した結果を更にHash()やforeachなどで整形しなければならないため。

やりたいこと

普通にassocで取ると

[0] => [
    ['id'] => 5,
    ['name'] => 'hoge',
],
[1] => [
    ['id'] => 14,
    ['name'] => 'fuga',
],

のように取れてしまうので、0、1・・・連番は必要ない。

fetchAll(PDO::FETCH_UNIQUE|PDO::FETCH_ASSOC)

[5] => [
    ['name'] => 'hoge'
],
[14] => [
    ['name'] => 'fuga',
],

どうやるか

use PDO;
use Cake\Datasource\ConnectionManager;
...

$connection = ConnectionManager::get('default');
$sql = "SELECT * FROM Hoge WHERE id <> ?";
$other_member = $connection->execute($sql, [$auth['id']])->fetchAll(PDO::FETCH_UNIQUE|PDO::FETCH_ASSOC);
pr($other_member);

PDOを使うのに、特にyumやcomposerなどでインストールは必要ない認識ですが環境によっては必要になるのかも知れません。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?