Laravel MySQL:将 SQL 查询翻译成 Laravel Eloquent

Laravel MySQL: translating SQL queries to Laravel Eloquent

我正在尝试为我的日程安排系统获取可用时间。我知道如何使用普通 SQL 查询来完成此操作,但我无法将查询转换为 Laravel Eloquent。我的查询如下所示

$query =  "SELECT * FROM schedules 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(function($query){
                    $query->whereBetween('time_end', [$start_datetime, $end_datetime]);
                })->get();

有什么正确的想法吗?我的 laravel eloquent 查询 Undefined variable: start_datetime

出现错误

谢谢

您需要使用 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();