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】orWhere()で任意の値が取れなかった場合に行った対策

Posted at

状況

LaravelのクエリビルダorWhereを使ってコードを書いていた際に、変換されるSQLで任意の値が取れずに苦戦しておりました。
書いていたコードと、実際に実行されていたSQLの主要な部分は以下の通りです。

コード

Laravel.php
 $Results = IfResult::join('aaa', 'bbb_id', '=', 'ccc.id')
      ->join('table', 'aaa.id', '=', 'bbb_id')
      ->orwhere('sample_column_a',  '>', 0)
      ->orWhere('sample_column_b', '', '')
      // 中略
      ->get();

実行されていたSQLで問題だった箇所

where 'sample_column_a' > ? or 'sample_column_b' <> ? and
where句の後をandまで( )で囲みたかったが、できていないせいで値が取れなかった。

修正したコード

orWhereの部分を以下のように修正しました。

Laravel.php
      ->orWhere(
        function ($query) {
          $query->orwhere('sample_column_a', '<>', '')
            ->orwhere('sample_column_b', '>', '0');
        }
      )

修正されたSQL

where ('sample_column_a' <> ? or 'sample_column_b' > ?) and

参考

Laravel5で「.. or ...) and (..」みたいな複雑な条件を書く

Laravel 5.7 データベース:クエリビルダ

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?