5
2

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 5 years have passed since last update.

LaravelのクエリビルダのOR条件をループで設定する

Posted at

以下のようなSQLをクエリビルダで設定する場合

SELECT
 *
FROM
 table
WHERE
 (column1 like '%test%'
 OR column2 like '%test%'
 OR column3 like '%test%'
 OR column4 like '%test%'
 OR column5 like '%test%')

こんな感じでできたのでメモ

$columns = [
  'column1',
  'column2',
  'column3',
  'column4',
  'column5',
];

$query->where(function ($query) use ($columns, $data) {
  $i = 0;
  foreach ($columns as $column) {
    $where = (!$i) ? 'where' : 'orWhere';
    $i++;
    $query->$where("table.{$column}", 'like', '%' . $data . '%');
  }
});
5
2
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
5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?