php Laravel Eloquent orWhere 查询
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27632236/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel Eloquent orWhere Query
提问by sarovarc
Can someone show me how to write this query in Eloquent?
有人可以告诉我如何在 Eloquent 中编写此查询吗?
SELECT * FROM `projects` WHERE `id`='17' OR `id`='19'
I am thinking
我在想
Project::where('id','=','17')
->orWhere('id','=','19')
->get();
Also my variables (17 and 19) in this case are coming from a multi select box, so basically in an array. Any clues on how to cycle through that and add these where/orWhere clauses dynamically?
在这种情况下,我的变量(17 和 19)也来自多选框,所以基本上是在一个数组中。关于如何循环并动态添加这些 where/orWhere 子句的任何线索?
Thanks.
谢谢。
回答by Damien Pirsy
You could do in three ways. Assume you've an array in the form
你可以通过三种方式来做。假设你有一个数组
['myselect' => [11, 15, 17, 19], 'otherfield' => 'test', '_token' => 'jahduwlsbw91ihp']
which could be a dump of \Input::all();
['myselect' => [11, 15, 17, 19], 'otherfield' => 'test', '_token' => 'jahduwlsbw91ihp']
这可能是一个转储 \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();
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();
回答by HTMHell
The best approach for this case is using Laravel's equivalent for SQL's IN()
.
这种情况下最好的方法是使用 Laravel 对 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 also more efficient - according to the Mysql Manual, if all values are constants, IN
sorts the list and then uses a binary search.
这种方法更好,也更有效 - 根据Mysql Manual,如果所有值都是常量,则IN
对列表进行排序,然后使用二进制搜索。
回答by kdlcruz
In laravel 5 you could do it this way.
在 Laravel 5 中,你可以这样做。
$projects = Projects::query();
foreach ($selects as $select) {
$projects->orWhere('id', '=', $select);
}
$result = $projects->get();
This is very useful specially if you have custom methods on your Projects model and you need to query from variable. You cannot pass $selects
inside the orWhere method.
如果您的项目模型上有自定义方法并且需要从变量中查询,这将非常有用。您不能$selects
在 orWhere 方法内部传递。