编写预订代码(API)

时间:2017-01-06 12:24:31

标签: 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');

关系在预订模型中:

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

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

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');
      }
}

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

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

然后在结束时,我希望得到类似['Car' => true, 'Car' => false]

的内容

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

更新

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

    return $appointments;
}

然后在我的控制器中

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]);
    }

1 个答案:

答案 0 :(得分: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);
    });
}

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

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

修改

我错过了所需的结束格式

  

[&#39;汽车&#39; =&GT;是的,&#39; Car&#39; =&GT;假]

因此,您可以通过删除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
        ];
    });
}

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