【问题标题】:Rent available cars from rentals table从租赁表中租用可用汽车
【发布时间】:2018-07-25 10:33:48
【问题描述】:

我有出租的桌子

id| user_id| car_id | starting_date | ending_date

这里是汽车桌

id | name

我不知道如何处理这种情况。我有 N 辆汽车,我只想退回特定日期的可用汽车。

例如我想在这个期间租车: 20.02.2018 - 23.02.2018

但我不知道如何使用 Laravel 检查每个案例以查看在该期间是否有车。

【问题讨论】:

    标签: php mysql database laravel


    【解决方案1】:

    使用whereDoesntHave() 方法。我假设您已经定义了rentals 关系:

    $date1 = Carbon::parse('20.02.2018')->startOfDay();
    $date2 = Carbon::parse('23.02.2018')->endOfDay();
    $available = Car::whereDoesntHave('rentals', function($q) use($date1, $date2) {
        $q->whereBetween('starting_date', [$date1, $date2])
          ->orWhereBetween('ending_date', [$date1, $date2])
          ->orWhere(function($q) use($date1, $date2) {
              $q->where('starting_date', '<', $date1)
                ->where('ending_date', '>', $date2);
          });
    })
    ->get();
    

    如果没有关系,在Car模型中定义:

    public function rentals()
    {
        return $this->hasMany(Rental::class);
    }
    

    【讨论】:

    • 感谢您的回答@Alexey Mezenin。但我猜这是一个问题。例如,现在在租金数据库中存在一个时期 18.02.2018 - 25.02.2018。我该如何处理这种情况,因为.. 这个日期不在 $date1 和 $date2 之间。
    • @Rince1934 也为此案例添加了逻辑。
    • 太好了!我想现在每个案例都提供了.. 还是?
    • 是的,现在所有案例都涵盖了。
    猜你喜欢
    • 2023-01-14
    • 1970-01-01
    • 1970-01-01
    • 2018-10-07
    • 2016-06-12
    • 1970-01-01
    • 1970-01-01
    • 2019-03-04
    • 2017-06-22
    相关资源
    最近更新 更多