LoginSignup
5
4

More than 5 years have passed since last update.

laravel5.4クエリビルダのwhereとorWhereをfor文で使う

Last updated at Posted at 2018-04-25

はじめに

渡されたキーワードの数によってwhere文を変えたいということがありました。
具体的には、2つ以上キーワードがあるときは、2つ目からはorWhereにするという感じです。
クエリビルダで書くと結構長くなりました。

コード

catsController.php
    public static function getName($keyWords)
    {
        $result = array();
        return $result = DB::table('Cats')
        ->select('Name')
        ->where(function ($query) use ($keyWords){
            if(count($keyWords) > 1)
            {
                $query->where('Description', 'like', "%$keyWords[0]%");
                for($i=1;$i<count($keyWords);$i++)
                {
                    $query->orWhere('Description', 'like', "%$keyWords[$i]%");
                }
            }
            else if(count($keyWords) == 1)
            {
                $query->where('Description', 'like', "%$keyWords%");
            }
        })
        ->orderBy('Name', 'asc')
        ->get();
    }
Catsテーブル
ID Name Description
1 blossom blossomは茶トラです。
2 bubbles bubblesは白と灰色です。
3 buttercup buttercupは茶トラです。

渡されたキーワードが1つだった場合と、1つを超える場合で出しわけをしています。
1つを超える場合は、そのキーワードの2つ目からはorWhereをfor文でまわしています。
発行されるSQLと実行結果は、以下のような感じになります。

キーワードが2つ以上だった場合

select Name from Cats where (Description like "%bubbles%" or Description like "%blossom%") order by Name asc
Name
blossom
bubbles

キーワードが1つだった場合

select Name from Cats where (Description like "%bubbles%") order by Name asc
Name
bubbles
5
4
3

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