0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

laravel (A) and (B or C)

Posted at

Laravel5のQueryBuilderは非常に便利ですが、複雑なwhere条件を書こうとするとwhereRawに頼ってしまいがちです。

しかし可読性を保つためなるべくwhereやorWhereで書いた方が良いと思います。

単純なAnd検索であれば、

$query->where('column1', '=', $value1)
->where('column2', '=', $value2)
単純なOr検索であれば、

$query->where('column1', '=', $value1)
->orWhere('column2', '=', $value2)

しかし、Laravel5を始めたばかりの人が必ず悩むのが(A or B) and (C or D)の条件です。

こういった複合系は次のようにクロージャで書けます。

$query->where(function($query) use($value1, $value2){
$query->where('column1', '=', $value1)
->orWhere('column2', '=', $value2)
});

$query->where(function($query) use($value3, $value4){
$query->where('column1', '=', $value3)
->orWhere('column2', '=', $value4)
});
useを使ってクロージャへ変数を渡してやるのがポイントです。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?