【CakePHP3】簡易あいまい検索
ドットインストールのCakePHP3レッスンにお世話になり始めて2日目。
基礎を学びつつ、応用して簡易あいまい検索機能(GET送信)を作りました。ブログを想定。タイトルにでも本文にでも検索ワードが含まれていれば該当記事がヒットする仕様。
# PostsController.php public function index() { if (isset($_GET['search'])) { # 検索ワードがGETで渡ってきていたら $posts = $this->Posts->find('all')->where([ 'OR' => [ ['title LIKE' => '%'.$_GET['search'].'%'], # 検索ワードが含まれるタイトルを検索 ['body LIKE' => '%'.$_GET['search'].'%'] # 検索ワードが含まれる本文を検索 ] ]); } else { # 検索実行前は全記事一覧表示 $posts = $this->Posts->find('all'); } $this->set(compact('posts')); }
# index.ctp <?= $this->Form->create(null, ['type' => 'get']); ?> <!-- GETで送信指定 --> <?= $this->Form->control('search', ['label' => 'キーワード検索', 'default' => $this->request->query('search')]); ?> <!-- 検索実行後にフォームに入力ワードを保持 --> <?= $this->Form->button('検索') ?> <?= $this->Form->end(); ?> <table> <tr> <th>ID</th> <th>タイトル</th> <th>本文</th> </tr> <?php foreach ($posts as $post) : ?> <tr> <td><?= h($post->id); ?></td> <td><?= $this->Html->link($post->title, ['action' => 'view', $post->id]); ?></td> <td><?= h($post->body); ?></td> </tr> <?php endforeach; ?> </table>
CakePHPはOR句の書き方が複雑でややこしいね。