ひとり勉強ログ

ITエンジニアの勉強したことメモ

#07 データベース操作の基本 Read:データの取得

前回、「Heroes」モデルを作成した。これを使用し、今回も引き続きデータベースへのアクセスの基本を行う。

  • Create:新規作成
  • Read:データの取得
  • Update:データの更新
  • Delete:データの削除

今回は、データの取得(Read)を行う。 Controller 内に「index」アクションとして追記、エンティティーの一覧データの取得を行う。 ※indexページにデータの一覧を表示させるイメージ。

「HeroesController」 に「index」アクションを追記

前回作成した「HeroesController」に、「index」アクションを追加する。

■場所 \htdocs\chococake\src\Controller ■ファイル名 HeroesController.php

[php] <?php namespace App\Controller;

use App\Controller\AppController;

/* * / class HeroesController extends AppController { public function add() { if ($this->request->is('post')) { $hero = $this->Heroes->newEntity(); $hero = $this->Heroes->patchEntity($hero, $this->request->data);

  if ($this-&gt;Heroes-&gt;save($hero)) {
    return $this-&gt;redirect(['action' =&gt; 'index']);
  }
}

}

// 今回追記部分。index アクション public function index() { $this->set('heores', $this->Heroes->find('all')); }

} [/php]

解説

[php] public function index() [/php] Controller 側に「index」メソッドを追加。

[php] $this->set('heores', $this->Heroes->find('all')); [/php] 「set」メソッドで第1引数「heores」に値を格納している。

保管している値は、第2引数の「$this->Heroes->find('all')」。

「$this->Heroes->find('all')」は「Heroes」の全エンティティーを取り出す処理。

「find」メソッドを使用することでデータ検索が簡単に行うことができる。引数に「all」と指定し、全エンティティーを取得している。

「find('all')」で得られたものはエンティティーの配列になっているので、そのまま 「set」メソッドで変数「heores」に格納している。

ビューテンプレートのファイル作成

ビューテンプレートファイルに一覧表示させる記述をする。

■場所 \htdocs\chococake\src\Template\Heroes ■ファイル名 index.ctp [php] <h1>データ取得</h1>

<table> <thead> <tr> <th>id</th> <th>名前</th> <th>超人強度</th> <th>出身地</th> </tr> </thead> <tbody> <?php foreach ($heroes as $hero): ?> <tr> <td><?= h($hero->id) ?></td> <td><?= h($hero->name) ?></td> <td><?= h($hero->power) ?></td> <td><?= h($hero->country) ?></td> </tr> <?php endforeach; ?> </tbody> </table> [/php]

解説

[php] <?php foreach ($heroes as $hero): ?> [/php]

Controller 側で「heroes」という名前に結果を格納していた。 この「heroes」から順にエンティティー値を取り出し、各フィールドの値を取り出す。 「$heroes」から取り出したデータを「$hero」に格納していく。

foreach の繰り返しの内部で <?= $hero->name ?> というようにエンティティーのプロパティを取り出す。

[php] <td><?= h($hero->id) ?></td> <td><?= h($hero->name) ?></td> <td><?= h($hero->power) ?></td> <td><?= h($hero->country) ?></td> [/php]

「h()」で囲んでいるのは、php の htmlspecialchars 関数。HTML関連のタグをエスケープしている。 CakePHP では「h 関数」として用意されている。

以下URLにアクセスすると前回追加したデータが表示される。 http://localhost/chococake/heroes/index