dongliao1949
2017-09-16 09:45
浏览 41
已采纳

Laravel MySQL:将SQL查询转换为Laravel Eloquent

I am trying to get time availability for my scheduling system. I know how to do it with plain SQL query but I am having trouble translating the query to Laravel Eloquent. My query is like the one below

$query =  "SELECT * FROM schedules WHERE (time_start BETWEEN '$start_datetime' AND '$end_datetime') OR (time_endBETWEEN '$start_datetime' AND '$end_datetime')";

and here's what I have tried with laravel eloquent so far

$sch = DB::table('schedules')
                ->where(function ($query) {
                    $query->whereBetween('time_start', [$start_datetime, $end_datetime]);
                })
                ->orWhere(function($query){
                    $query->whereBetween('time_end', [$start_datetime, $end_datetime]);
                })->get();

any ideas how to do it right? I am getting an error with my laravel eloquent query Undefined variable: start_datetime

Thanks

图片转代码服务由CSDN问答提供 功能建议

我正在尝试为我的调度系统获取时间可用性。 我知道如何使用纯SQL查询来完成它,但我无法将查询转换为Laravel Eloquent。 我的查询类似于下面的那个

  $ query =“SELECT * FROM schedule WHERE(time_start BETWEEN'$ start_datetime'AND'$ end_datetime')OR(time_endBETWEEN'$ start_datetime'  AND'$ end_datetime')“; 
   
 
 

这是我到目前为止用laravel eloquent试过的东西

   $ sch = DB :: table('schedules')
  - > where(function($ query){
 $ query-> whereBetween('time_start',[$ start_datetime,$ end_datetime]); 
}  )
  - > orWhere(函数($ query){
 $ query-> whereBetween('time_end',[$ start_datetime,$ end_datetime]); 
}) - > get(); 
 <  / code>  
 
 

任何想法如何做对吗? 我的laravel eloquent查询错误未定义变量:start_datetime

谢谢

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douyi6168 2017-09-16 09:48
    已采纳

    You need to call the variables to closure scope by using use

    $sch = DB::table('schedules')
                    ->where(function ($query) use ( $start_datetime,$end_datetime) {
                        $query->whereBetween('time_start', [$start_datetime, $end_datetime]);
                    })
                    ->orWhere(function($query) use ( $start_datetime,$end_datetime){
                        $query->whereBetween('time_end', [$start_datetime, $end_datetime]);
                    })->get();
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题