laravel 5,具有多个值的 where 子句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32997432/
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 5, where clause with multiple values
提问by mrbrightside
I wanted to pass all $id values to the where clause, 3rd line from the code below. but as i'am trying to return $friend it is null. am i addressing the $id values incorrectly? or i got it wrong in the query? i checked my database and it should return 2 rows.
我想将所有 $id 值传递给下面代码的第 3 行 where 子句。但当我试图返回 $friend 时,它是空的。我是否错误地处理了 $id 值?还是我在查询中弄错了?我检查了我的数据库,它应该返回 2 行。
i also checked $id by returning it and it returns what i am expecting and i guess i got it wrong in the query in $friend line.
我还通过返回它来检查 $id 并且它返回我期望的内容,我想我在 $friend 行的查询中弄错了。
$x = user->id;
$id = DB::table('requests')->select('id')->where('id', '=', $x)->get();
$friend = DB::table('users')->where('id', 'in', $id)->get();
回答by Yasen Slavov
You need to use whereIn()
, and maybe a better option for the whole deal would be:
您需要使用whereIn()
,也许整个交易的更好选择是:
$ids = DB::table('requests')->where('id', $x)->lists('id');
$friend = DB::table('users')->whereIn('id', $ids)->get();
Note that the second parameter of whereIn() needs to be an array.
注意 whereIn() 的第二个参数需要是一个数组。
回答by Joseph Silber
You can do it all in a single query:
您可以在一个查询中完成所有操作:
$friends = DB::table('users')->whereIn('id', function ($query) use ($user) {
$query->select('id')->from('requests')->where('id', $user->id);
})->get();
回答by ArjanSchouten
What you want is whereIn
(scroll down a bit). It's also possible to use whereNotIn
.
你想要的是whereIn
(向下滚动一点)。也可以使用whereNotIn
.
$userIds = [1, 2, 3];
$friend = DB::table('users')->whereIn('id', $userIds)->get();
Or whereNotIn
:
或whereNotIn
:
$userIds = [1, 2, 3];
$friend = DB::table('users')->whereIn('id', $userIds)->get();
Take a look at all the possible advanced where clauses which are supported by the Laravel query builder.
查看 Laravel 查询构建器支持的所有可能的高级 where 子句。