这些数据库语句如何更有表现力和说服力?

时间:2019-07-11 14:21:42

标签: php database laravel eloquent

首先,我认为这个问题需要很多时间来考虑它,并且如果您真的很乐意这样做,希望您处理它。

这是我的问题:

我使用Laravel创建了用于车辆的预订系统,其中有一个欢迎页面,其中包含一个表单,该表单可让用户输入位置以及预订的开始和结束日期。提交表单后,用户将被转到显示指定位置和时间段内所有可用汽车的站点。

以下是检查哪些汽车可用的代码:

public function findCar(Request $request)
{
    //Validating the Data
    $this->validate($request,[
        'Standort' => 'bail|required',
        'Startdatum' => 'bail|required|date',
        'Enddatum' => 'bail|required|date|after_or_equal:Startdatum'
    ]);

    //Get all the data from the form
    $start = Input::get('Startdatum',false);
    $end = Input::get('Enddatum',false);
    $place = Input::get('Standort',false);
    $start = strtotime($start);
    $end = strtotime($end);

    //Getting all cars from the given city
    $city_id = City::where('name','=',$place)->get('id');
    $carsCity = Car::where('id_currentCity','=',$city_id[0]->id)->get();

    //Getting the IDs of the cars that collide with the given time period 
    $collidingBookings = Booking::where('begin','<',$end)->where('end','>',$start+86399)->get();
    $partiallyCollidingBookings = Booking::where('begin','<',$end+86399)->where('end','>=',$start)->get();

    $collidingID = array();
    foreach ($collidingBookings as $collidingBooking){
        array_push($collidingID,$collidingBooking->id_car);
    }

    $partiallyCollidingID = array();
    foreach ($partiallyCollidingBookings as $partiallyCollidingBooking){
        array_push($partiallyCollidingID,$partiallyCollidingBooking->id_car);
    }

    //Getting the available cars, which bookings are not even partially colliding with other bookings and the partially available cars that are not colliding fully
    $availableCars = $carsCity->whereNotIn('id',$partiallyCollidingID);
    $partiallyAvailableCars = $carsCity->whereNotIn('id',$collidingID)->diff($availableCars);        

    return view('pages.findCar',[
        'place' => $place,
        'start' => $start,
        'end' => $end,
        'availableCars' => $availableCars,
        'partiallyAvailableCars' => $partiallyAvailableCars
    ]);
}

我的代码看起来很糟糕,查询也不是很有效。在此预订系统中,一次会有很多汽车,很少有预订。我认为最好先从指定位置取回所有汽车,然后根据指定的时间段和可用性对它们进行分类。

是否有更好的方法来检索可用的汽车?如果没有,是否有办法使我的代码更简洁?

1 个答案:

答案 0 :(得分:0)

雄辩已针对性能进行了优化,但如果遵循雄辩的关系标准,则可以提高性能。 https://laravel.com/docs/5.8/eloquent

您的答案也可以在这里找到。 Laravel Eloquent vs query builder - Why use eloquent to decrease performance