LoginSignup
0
0

More than 1 year has passed since last update.

cakePHP4 複数絞り込み・検索機能実装

Posted at

Every Qiita #23
のんびり独学初学者投稿 23日目
今回は・・・
cakePHP4の絞り込みと複数条件で検索機能を実装した時の備忘録です。

完全一致を5つ・部分一致を1つ・空の場合は除外する

今回はポートフォリオで合同トレーニングのマッチングサービスを開発しており、絞り込みを実装している時のメモになります。
検索条件は以下の通りです。

検索項目 テーブル.カラム
日時 Collects.time
ジム  Gyms.id
ターゲット Purposes.id
住所 Prefectures.id
トレーニング部位 Parts.id
店舗・施設(部分一致) Collects.city

処理フローを考える

  1. formから入力されたデータをコントローラ/indexアクションに送る
  2. 検索データが送られたかを判定し、条件分岐する
    1. データ有:空を排除し、入力されたデータのみ格納
    2. データ無:find('all')で全件取得
  3. whereは連想配列で設置するため、入力データを連想配列(キーに検索対象・条件、値に入力データ)として格納。
  4. クエリを実行しセットする

上記のフローで実装していこうと思います。

index.php
<?= $this->Form->create(null, ['type' => 'get', 'url' =>['action' => 'index','controller' => 'Collects']]); ?>
<?= $this->Form->hidden("filter",["value"=>"filter"]); ?>
<!-- 省略 -->
<?= $this->Form->submit(__("絞り込み")); ?>
<?= $this->Form->end();?>

inputのhiddenで検索された時のみに与える値を設置します。

任意Controller.php
if ($this->request->getQuery('filter')) {
    // where文のデータを取得(空も含む)
    $getQuery = [];
    $getQuery["Collects.time"] = $this->request->getQuery("date");
    $getQuery["Gyms.id"] = $this->request->getQuery("gym_id");
    $getQuery["Purposes.id"] = $this->request->getQuery("purpose_id");
    $getQuery["Prefectures.id"]= $this->request->getQuery("prefecture_id");
    $getQuery["Parts.id"] = $this->request->getQuery("part_id");
    $getQuery["Collects.city LIKE"] = "%".$this->request->getQuery("city")."%";

    // 検索されたデータのみ形成しwhere実行
    $filter=[];
    foreach($getQuery as $key => $val){
        if(!empty($val)){
            $filter[$key] = $val;
        }
    }
    $query = $this->Collects->find();
    $query->where([$filter]);

    // クエリ実行
    $collects = $this->paginate($query);
}else{
    $collects = $this->paginate($this->Collects->find('all'));
}

  1. hiddenの値が確認できれば連想配列に格納します
  2. getQueryで送られたデータを取得できますが、空の状態もあるのでforeachで値が存在するもののみで新たに成形します。cityは部分一致なので、キーにLIKEを入れています
  3. whereの中に連想配列を入れ、条件にあった募集のみを取得します。

あまり時間がない中で実装したので、微妙な感じでの実装になってしまっております・・・:cry:
他に最適な方法ご存知の方いらっしゃいましたらご教示頂ければと思います:smile:

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