Laravel雄辩:类Closure的对象无法转换为字符串连接查询

我正在尝试获取在所选日期没有预订的所有车辆:

 $bookings = Booking::all();
 $vehicles = Vehicle::all();

 $selectedStart = Carbon::createFromFormat('d/m/Y H:i',  $request['start']);
 $selectedEnd =  Carbon::createFromFormat('d/m/Y H:i',  $request['end']);


 $availableVehicles = $vehicles->join('bookings', function ($join){
        $join->on('vehicles.id', '=', 'bookings.vehicle_id')
            ->where([
                    ['bookings.start', '<',$selectedStart],
                    ['bookings.end', '<', $selectedStart]
                ])->orWhere([
                    ['bookings.start', '>',$selectedEnd],
                    ['bookings.end', '>', $selectedEnd]
                ]);
  })->get();

但我收到以下错误:

Closure类的对象无法转换为字符串
评论
  • ciste
    ciste 回复

    use query() method here instead of all() method because all() method get rows from database and store into collection..

    $bookings = Booking::query();
    $vehicles = Vehicle::query();
    
    $selectedStart = Carbon::createFromFormat('d/m/Y H:i',  $request['start']);
    $selectedEnd =  Carbon::createFromFormat('d/m/Y H:i',  $request['end']);
    
    
    $availableVehicles = $vehicles->join('bookings', function ($join) use ($selectedStart,$selectedEnd){
            $join->on('vehicles.id', '=', 'bookings.vehicle_id')
                ->where([
                        ['bookings.start', '<',$selectedStart],
                        ['bookings.end', '<', $selectedStart]
                    ])->orWhere([
                        ['bookings.start', '>',$selectedEnd],
                        ['bookings.end', '>', $selectedEnd]
                    ]);
    })->get();