编写预订代码(API)

leo*_*019 8 php mysql laravel laravel-5.3

我已经完成了我正在处理的大部分应用程序,现在我觉得我陷入了一个变化.我有这样做的想法,但问题我真的无法实现它.我希望我能在这里找到一些帮助.

我有这个复杂的代码.它需要两个日期并检查car_reservation数据透视表是否重叠.

 $table->integer('car_id')->unsigned();
 $table->foreign('car_id')->references('id')->on('cars');

 $table->integer('reservation_id')->unsigned();
 $table->foreign('reservation_id')->references('id') >on('reservations');
Run Code Online (Sandbox Code Playgroud)

关系在预订模型中:

 public function cars()
{
    return $this->belongsTo('App\Models\Access\Car','car_reservation');
}
Run Code Online (Sandbox Code Playgroud)

这是我正在尝试调试并使其工作的代码:

public function get(Request $request)
{

   $appointments = Reservation::with('cars')->get();

   foreach ($appointments as $appointment) {

     $from = Carbon::parse($request->from);
     $to = Carbon::parse($request->to);
     $eventStart = Carbon::instance(new DateTime($appointment['dt_start']));
     $eventEnd = Carbon::instance(new DateTime($appointment['dt_end']))->subSecond(1);

     // A spot is taken if either the from or to date is between eventStart and eventEnd
     // or if the evenStart and eventEnd are between the from and to date.

      if ($from->between($eventStart, $eventEnd) || 
       $to->between($eventStart, $eventEnd) ||
      ($eventStart->between($from, $to) &&
       $eventEnd->between($from, $to))) {
            return response()->json('false');// test response 
      }
            return response()->json('no appointments overlapping');
      }
}
Run Code Online (Sandbox Code Playgroud)

但我需要帮助的是编写这些步骤,我认为它会完美运行.

(1)从car_reservation可选日期范围内获取appoitmenets的方法.例如:getAppointments($from=null,$to=null

(2)循环所有汽车并将它们排列成阵列的方法.例如:getCars

(3)检查可用性的方法.例如:isSlotAvailable($from,$to,$appoitments);

(4)完成工作的方法:

function getAvailability(Request $request)
{
    $slots = [];

    $from = $request->input('from');

    $to = $request->input('to');

    foreach ($this->getcars() as $cars) {

        $appointments = $this->getAppointments($cars, $from, $to);

        $slot[$cars] = $this->isSlotAvailable($from, $to, $appointments);
    }

    return $slots;
}
Run Code Online (Sandbox Code Playgroud)

然后在最后我希望得到类似的东西 ['Car' => true, 'Car' => false]

你的帮助将非常感激.我已经提出了许多代码,但它们看起来都像我的原始代码.

UPDATE

public static function findAppointmentsBetweenDates($start, $end)
{
    $appointments = Reservation::wherenotBetween('from_date',array($start,$end))->get();

    return $appointments;
}
Run Code Online (Sandbox Code Playgroud)

然后在我的控制器中

public function get(Request $request)
{
    $results = array();

    $car = Car::doesntHave('reservations')->get();


    if (!$car->isEmpty()) {
        $results[] = $car;

        return Response::json(['array'],$results);
    }


$from = Carbon::parse($request->from)->addHour(2);
    $to = Carbon::parse($request->to);

    $appointmentsBetweenDates = Reservation::findAppointmentsBetweenDates($from, $to);

    foreach ($appointmentsBetweenDates as $appointment)
    {
        $results = ($appointment->cars);


    }
    return Response::json(['array',$results]);
    }
Run Code Online (Sandbox Code Playgroud)

nkc*_*nor 2

我们可以利用数据库的强大功能来过滤时段内可用的汽车。使用查询生成器,我们可以查找在指定窗口期间没有预订的每辆汽车。

在Car

/**
 * @param $from Carbon
 * @param $to Carbon
 * @return \Illuminate\Database\Eloquent\Collection
 */
public static function whereAvailableBetween($from, $to) {
    $rows = DB::table('car')
        ->leftJoin('car_reservation', 'car_reservation.car_id', '=', 'car.id')
        ->leftJoin('reservation', function($join) use ($from, $to) {
            return $join->on('reservation.id', '=', 'car_reservation.reservation.id')
                ->where('reservation.date_start', '>=', $from->toDateTimeString())
                ->where('reservation.date_end', '<=', $to->toDateTimeString());
        })
        ->whereNull('reservation.id')
        ->get();

    return $rows->map(function($r, $k) {
        return new static($r);
    });
}
Run Code Online (Sandbox Code Playgroud)

现在,我们可以使用\Car::whereAvailableBetween($date_start, $date_end). 要从控制器将其作为 JSON 返回,您可以:

public function get(Request $request)
{
    return Car::whereAvailableBetween(Carbon::parse($request->from), Carbon::parse($request->to));
}
Run Code Online (Sandbox Code Playgroud)

编辑

我错过了所需的结束格式是

[“汽车”=> true,“汽车”=> false]

因此,您可以修改上述方法并通过删除子句返回包含这些详细信息的标准集合whereNull:

/**
 * @param $from Carbon
 * @param $to Carbon
 * @return \Illuminate\Support\Collection
 */
public static function whereAvailableBetween($from, $to) {
    $rows = DB::table('car')
        ->leftJoin('car_reservation', 'car_reservation.car_id', '=', 'car.id')
        ->leftJoin('reservation', function($join) use ($from, $to) {
            return $join->on('reservation.id', '=', 'car_reservation.reservation.id')
                ->where('reservation.date_start', '>=', $from->toDateTimeString())
                ->where('reservation.date_end', '<=', $to->toDateTimeString());
        })
        ->select('car.*', 'reservation.id AS reservation_id')
        //->whereNull('reservation.id') if it is null then no reservation, else there is a reservation
        ->get();

    return $rows->map(function($row, $k) {
        $asArray = (array)$row;
        $reservation_id = array_pop($asArray);
        $available = (is_null($reservation_id)) ? true: false;

        return [
            'car' => new static($asArray),
            'available' => $available
        ];
    });
}
Run Code Online (Sandbox Code Playgroud)

请记住,您还可以向模型添加属性。所以我们可以做 $car->available = true