简体   繁体   中英

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();

Print Screen: 在此处输入图片说明

I don't know why $ot_start and $ot_end getting error.

Add 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 . 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 . That's why phpstorm marks these variables, as they're undefined in function's scope.

You need to pass'em explicitly with use word:

OTMain::with(['otmain_many_otline'=>function($query) use ($ot_start, $ot_end) {

Now, these variables are available in function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM