laravel 查询生成器:将参数传递给匿名函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15007161/
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
Query builder: passing argument to anonymous function
提问by petwho
I got a problem in passing variable to query builder closure, here is my code:
我在将变量传递给查询构建器闭包时遇到问题,这是我的代码:
function get_usersbyname($name){
dd($name);
$resultset = DB::table('users')->where(function($query){
$query->where('username', 'LIKE', $name);
});
....
}
if I run it, it returns an error "undefined name variable
", but I already passed $name
variable and checked its existence.
Also I cann't find any resouce explains how to pass variable to query builder anonymous function.
Could you help me with this problem?
如果我运行它,它会返回一个错误“ undefined name variable
”,但我已经传递了$name
变量并检查了它的存在。此外,我找不到任何解释如何将变量传递给查询构建器匿名函数的资源。你能帮我解决这个问题吗?
回答by Aran
You need to the tell the anonymous function to use that variable like...
您需要告诉匿名函数使用该变量,例如...
Because that variable is outside the scope of the annonymous function it needs to be passed in using the usekeyword as shown in the example below.
因为该变量在匿名函数的范围之外,所以需要使用use关键字传入,如下例所示。
function get_usersbyname($name){
dd($name);
$resultset = DB::table('users')->where(function($query) use ($name) {
$query->where('username', 'LIKE', $name);
});
....
}