ひとり勉強ログ

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

#09 データベース操作の基本 Delete:データの削除

前回、「Heroes」モデルの「データの更新」を行った。今回はデータの削除を行う。

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

データの削除はデータの更新とほぼ同じ。

アクセス時に渡された id をもとにエンティティーを検索して削除する。

Heroes」コントローラーに「delete」アクションを追記

「HeroesController」に、「delete」アクションを追加する。

■場所 \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('heroes', $this->Heroes->find('all')); }

// editアクション public function edit($id = null) { $hero = $this->Heroes->get($id); if ($this->request->is(['post', 'put'])) { $hero = $this->Heroes->patchEntity($hero, $this->request->data); if ($this->Heroes->save($hero)) { return $this->redirect(['action' => 'index']); } } else { $this->set('hero', $hero); } }

// 今回追記部分。deleteアクション public function delete($id = null) { $hero = $this->Heroes->get($id); if ($this->request->is(['post', 'put'])) { if ($this->Heroes->delete($hero)) { return $this->redirect(['action' => 'index']); } } else { $this->set('hero', $hero); } }

} [/php]

解説

[php] public function delete($id = null) [/php] edit アクションと同様に delete アクションの引数に id を指定する。指定することで id のレコードの情報を呼び出し、表示させることができる。

例として id が「1」のレコードを表示させるためには、「/chococake/heroes/delete/1」にアクセスすればよい。

[php] if ($this->request->is(['post', 'put'])) { if ($this->Heroes->delete($hero)) { [/php] post 送信された場合に delete メソッドでエンティティーのレコードを削除する。

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

ビューテンプレートファイルに削除確認画面を表示させる記述をする。

■場所 \htdocs\chococake\src\Template\Heroes ■ファイル名 delete.ctp

[php] <h1>削除</h1>

<!-- フォーム開始タグ --> <?= $this->Form->create($hero) ?>

<!-- フォームの入力内容をグループ化するタグ --> <fieldset> <!-- 各入力フィールドのinputタグ --> <p><?= h($hero->id); ?></p> <p><?= h($hero->name); ?></p> <p><?= h($hero->power); ?></p> <p><?= h($hero->country); ?></p> </fieldset>

<!-- 送信ボタンのタグ --> <?= $this->Form->button('削除') ?>

<!-- フォーム終了タグ --> <?= $this->Form->end() ?> [/php]

解説

create メソッド $hero を引数にしてフォームを生成。

その中に削除対象となるエンティティーの値を出力している。

このフォームは何か値を送信するのではなく、delete アクションに post 送信するという役割を持つのみ。

以下URLにアクセスすると削除確認画面が表示される。 http://localhost/chococake/heroes/delete/1

「編集」ボタンを押下し、「/chococake/heroes/」にリダイレクトされればOK。

これでデータベース操作の基本となる CRUD のすべての処理が実装された。