LoginSignup
2
5

More than 5 years have passed since last update.

CakePHP3 Find使い方

Last updated at Posted at 2016-12-24

Finderをカスタマイズ

コントローラーでFindのMethod名を入力
findの最初のパラメータにMethod名を決める。

find('XXX')に名前を指定した場合、コントローラーはTableに「findXXX」名のMethodを追加して実装する必要があります。

例)タグしたBookmark情報を取得したい場合taggedと言う名前を入力した場合
コントローラーはBookmarksTableに「findTagged」名のMethodがあるか探して実行する。

コントローラーは単純にTableのデータ取得Methodを呼ぶだけ。 
実際データを作る役はTableが担当。Method名もfindXXX形式になるので見やすい。
以下のソースはCakePHP公式サイトから参考

BookmarksController.php
    public function tags() {
        $tags = $this->request->params['pass'];
        $bookmarks = $this->Bookmarks->find('tagged', [
            'tags' => $tags
        ]);
        $this->set([
            'bookmarks' => $bookmarks,
            'tags' => $tags
        ]);
    }

モデル(Table)に上記の名前でMethod定義

BookmarksTable.php
       public function findTagged(Query $query, array $options){

        return $this->find()
            ->distinct(['Bookmarks.id'])
            ->matching('Tags', function($q) use($options) {
           if(empty($options['tags'])){
               return $q->where(['Tags.title IS' => null]);
           }
           return $q->where(['Tags.title IN' => $options['tags']]);
        });
    }

こんな感じで実装すればコントローラーは簡単、実際ロジックはTableで実装するため見やすくなりそう
以下参考
http://book.cakephp.org/3.0/ja/index.html

2
5
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
2
5