Laravel Rloquent orWhere Query

Can someone show me how to write this query in Eloquent?

SELECT * FROM `projects` WHERE `id`='17' OR `id`='19' 

I think

 Project::where('id','=','17') ->orWhere('id','=','19') ->get(); 

Also, my variables (17 and 19) in this case come from the multi select block, so basically in the array. Any tips on how to loop through them and add them where / or where clauses dynamically?

Thanks.

+5
source share
3 answers

You can do this in three ways. Suppose you have an array in the form

['myselect' => [11, 15, 17, 19], 'otherfield' => 'test', '_token' => 'jahduwlsbw91ihp'] , which may be a dump \Input::all();

  •   Project::where(function ($query) { foreach(\Input::get('myselect') as $select) { $query->orWhere('id', '=', $select); } })->get(); 
  •   Project::whereIn('id', \Input::get('myselect'))->get(); 
  •   $sql = \DB::table('projects'); foreach (\Input::get('myselect') as $select) { $sql->orWhere('id', '=', $select); } $result = $sql->get(); 
+15
source

The best approach for this case is to use the Laravel equivalent for SQL IN() .

 Project::whereIn('id', [17, 19])->get(); 

Will be the same as:

 SELECT * FROM projects WHERE id IN (17, 19) 

This approach is nicer and more efficient - according to the Mysql Guide , if all values ​​are constants, IN sorts the list and then uses a binary search.

+9
source

In laravel 5 you can do it this way.

 $projects = Projects::query(); foreach ($selects as $select) { $projects->orWhere('id', '=', $select); } $result = $projects->get(); 

This is very useful, especially if you have custom methods in your project model and you need to request a variable. You cannot pass $selects inside an orWhere method.

+1
source

Source: https://habr.com/ru/post/1209815/


All Articles