如何解决将带有变量的闭包传递给Laravel查询构建器中的where方法
根据Laravel文档,可以通过将闭包作为第一个参数传递给orWhere方法来对“或”条件进行分组:
$users = DB::table('users')
->where('votes','>',100)
->orWhere(function($query) {
$query->where('name','Abigail')
->where('votes',50);
})
->get();
我想要的是在查询中使用一个变量,它看起来像:
$q = $request->get('query');
$users = DB::table('users')
->where('votes',100)
->orWhere(function($query) {
$query->where('name',$q)
->where('votes',50);
})
->get();
我试图将其作为第二个参数传递,例如:
$q = $request->get('query');
$users = DB::table('users')
->where('votes',100)
->orWhere($q,function($query,$q) {
$query->where('name',50);
})
->get();
但是它不起作用,有什么帮助吗?
解决方法
您需要使用use()
函数将数据传递到更近的位置
引用链接In PHP,what is a closure and why does it use the "use" identifier?
$q = $request->get('query');
$users = DB::table('users')
->where('votes','>',100)
->orWhere(function ($query) use($q) { // use function to pass data inside
$query->where('name',$q)
->where('votes',50);
})
->get();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。