Symfony Expr条件メソッド
リポジトリに独自メソッドを追加し、その際にはExprを使用して条件指定すべきことを学びました。 その際Exprの条件用メソッドがいくつかあったのでここにまとめておきます。
Expr条件指定メソッド
条件 | 書き方 |
---|---|
フィールド= 値 | 《Expr》->eq( カラム名, 値 ) |
フィールド <> 値 | 《Expr》->neq( カラム名, 値 ) |
フィールド < 値 | 《Expr》->lt( カラム名, 値 ) |
フィールド <= 値 | 《Expr》->lte( カラム名, 値 ) |
フィールド > 値 | 《Expr》->gt( カラム名, 値 ) |
フィールド >= 値 | 《Expr》->gte( カラム名, 値 ) |
フィールド LIKE 値 | 《Expr》->like( カラム名, 値 ) |
フィールド NOT LIKE 値 | 《Expr》->notLike( カラム名, 値 ) |
フィールド IN 配列 | 《Expr》->in( カラム名, 配列 ) |
フィールド NOT IN 配列 | 《Expr》->notIn( カラム名, 配列 ) |
フィールド IS NULL | 《Expr》->isNull( カラム名) |
フィールド IS NOT NULL | 《Expr》->isNotNull( カラム名) |
Exprを使わないで書く時
<? php class PersonRepository { public function findByName($value) { $arr = explode (',', $value); //第1引数の文字で第2引数の文字列を配列に分割する関数 return $this->createQueryBuilder('p') // Personテーブルをpと指定 ->where("p.name in (?1, ?2)") ->setParameters(array(1 => $arr[0], 2 => $arr[1])) ->getQuery() // Queryクラスのインスタンスを取得 ->getResult(); // 実行(エンティティのリストを返す) } } ?>
Exprを使って書く時
<? php class PersonRepository { public function findByName($value) { $arr = explode(',', $value); $builder = $this->createQueryBuilder('p'); // buidlerを変数に代入 return $builder // builderのwhereメソッドを呼び出す形にする ->where($builder->expr()->in('p.name', $arr)) ->getQuery() ->getResult(); } } ?>
in式の時はパラメータをいちいちセットする手間が減る!
x <> 1
このような不等号は初めて知りました。
x < 1 かつ x > 1
という意味、つまり x != 1
と覚えておいて良さそう。