php - 编写预订代码(API)

标签 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 获取预约信息的方法。例如: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;
}

然后在我的 Controller 中

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

最佳答案

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

汽车

/**
 * @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)。要从您的 Controller 将其作为 JSON 返回,您可以:

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

编辑

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

['Car' => true, 'Car' => 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
        ];
    });
}

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

关于php - 编写预订代码(API),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41505686/

相关文章:

mysql - 列出每个玩家的前5个得分的平均值

mysql - 什么对性能和可读性更好 : a status column with boolean type or varchar?

php - 如何处理 Blade 模板中的一对多关系?

php - 覆盖 laravel 验证消息

php - 将 PayPal 集成到注册系统中的最简单方法是什么?

php - 如何使用 PHP Laravel 从 Outlook API 下载附件?

php - 将内容加载到应用程序的最佳方式

php - PHP CLI 的优点?

php - 获取主题+上一个发帖者的用户名

mysql - MySQL中如何随机选择列和满足条件的行