[英]How to use condition for one to many relationship in Laravel 5.4
I follow this link and its work well, but when I try to put a variable its give me syntax error. 我按照此链接操作 ,但效果很好,但是当我尝试放入变量时,它给了我语法错误。
Here's my Code: 这是我的代码:
$ot_start = $request->ot_start;
$ot_end = $request->ot_end;
$ot_list = OTMain::with(['otmain_many_otline'=>function($query){
$query ->where('time_from', '>=', date('d/M/Y H:i:s', strtotime($ot_start . ' 00:00:00.000')))
->where('time_from', '<=', date('d/M/Y H:i:s', strtotime($ot_end .' 23:59:59.000')));
}])->get();
I don't know why $ot_start and $ot_end getting error. 我不知道为什么$ ot_start和$ ot_end出现错误。
Add use(): 添加use():
$ot_list = OTMain::with(['otmain_many_otline'=>function($query) use (ot_start , ot_end ){
$query ->where('time_from', '>=', date('d/M/Y H:i:s', strtotime($ot_start . ' 00:00:00.000')))
->where('time_from', '<=', date('d/M/Y H:i:s', strtotime($ot_end .' 23:59:59.000')));
}])->get();
If you use closures (anonymous functions) you need pass your variables by use
. 如果使用闭包(匿名函数),则需要
use
传递变量。 Eg: 例如:
$ot_start = $request->ot_start;
$ot_end = $request->lot_end;
$ot_list = OTMain::with(['otmain_many_otline'=>function($query) use($ot_start,$ot_end){
$query ->where('time_from', '>=', date('d/M/Y H:i:s', strtotime($ot_start . ' 00:00:00.000')))
->where('time_from', '<=', date('d/M/Y H:i:s', strtotime($ot_end .' 23:59:59.000')));
}])->get();
Anonymous function function($query)
knows nothing about $ot_start
, $ot_end
. 匿名函数
function($query)
一无所知 $ot_start
, $ot_end
。 That's why phpstorm marks these variables, as they're undefined in function's scope. 这就是phpstorm标记这些变量的原因,因为它们在函数作用域中未定义。
You need to pass'em explicitly with use
word: 您需要
use
单词显式地传递它们:
OTMain::with(['otmain_many_otline'=>function($query) use ($ot_start, $ot_end) {
Now, these variables are available in function. 现在,这些变量在功能中可用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.