我正在尝试使用 laravel-eloquent 获取特定日期之后的房间和他们的预订。
$fdate='2015-01-05';
$roomdata=Rooms::where('city_id','=',$citydata['id'])
->with('types')
->with('localities')
->with('slideshow')
->with(array('booking' => function($query){
$query->where('bookstart','>',$fdate);
}))
->get();
这给我一个错误,说 $fdate
未定义。但是当我这样做的时候
$query->where('bookstart','>','2015-01-05');
这很好用。这背后有什么原因吗?有人可以为这个问题提供一个好的解决方案吗?
最佳答案
您正在使用 closure在 with
的回调中。首先,引用该文档页面:
Closures may also inherit variables from the parent scope. Any such variables must be passed to the use language construct.
您正试图从匿名函数中的父作用域访问一个变量,因此您必须首先将它传递给 use
构造,以便让 PHP 知道您正在围绕该变量创建闭包:
$roomdata = Rooms::where('city_id','=',$citydata['id'])
->with('types')
->with('localities')
->with('slideshow')
->with(array('booking' => function($query) use($fdate) {
$query->where('bookstart','>',$fdate);
}))
;
将此与 Javascript 进行对比,Javascript 允许程序员自动访问父作用域,因为每个子作用域都是父作用域的 Scope Chain 的一部分。 .像这样的东西在 Javascript 中是有效的:
var foo = 'bar';
(function() {
alert(foo);
})();
在 PHP 中,从内部函数中获取对外部变量的访问不是自动的。这样,PHP 就区分了closures and anonymous functions。 (又名“lambdas”)以 JavaScript 所没有的方式,至少在语法方面是这样。然而,这在文档中没有明确说明(手册似乎将两者等同起来,但实际上它们并不相同)。
关于php - 没有识别变量的 Laravel Eloquent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27783111/