【问题标题】:Laravel | retrieving collection with relationship and except specific Ids拉拉维尔 |检索具有关系的集合,但特定 ID 除外
【发布时间】:2019-06-17 13:14:39
【问题描述】:

我正在为汽车租赁预订系统工作 所以我的计划是当客户搜索所选车型中是否有可用汽车时, 首先:获取客户选择的日期的汽车ID 第二:得到所有的汽车,除了不可用的汽车,

$collection = Booking::whereDate('dropoffday', '>' ,$date1)
        ->whereDate('pickupday' ,'<', $date2)
        ->get(['car_id'])
    ;
    if ($collection->isEmpty()) {

        $cars = Car::with('marques.images')->get();
        return Response::json($cars);
    }
    $taken = [];
    foreach ($collection as $car) {
        $id = $car->car_id;
        array_push($taken,$id);
    }
    $cars = Car::with('marque.images')->except($taken);
    return Response::json($cars);
}

我该如何重写这一行 $cars = Car::with('marque.images')->except($available); 获取所有有关系的汽车,除了不可用的汽车

【问题讨论】:

  • 也许doesntHave方法可以帮助你laravel.com/docs/5.7/…
  • BookingCar是什么关系?
  • BookingbelongTo Car and Car BelongsToMany Booking
  • 我把它当作汽车的功能 -> 预订关系称为bookings?我用这个信息更新我的答案
  • 是的叫做预订,我应该使用BelongsToMany而不是hasMany吗?

标签: php laravel


【解决方案1】:

如果您的关系设置正确,您可能可以像这样使用whereDoesntHave 方法:

$cars = Car::with('marque.images')->whereDoesntHave('bookings', function ($query) use ($date1, $date2) {
    $query->whereDate('dropoffday', '>' ,$date1)
        ->whereDate('pickupday' ,'<', $date2);
})->get();
return Response::json($cars);

【讨论】:

  • $date1$date2 未定义
  • 我从 ajax 查询中得到 date1 和 date2
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-06
  • 2022-10-14
  • 1970-01-01
  • 2021-06-07
  • 1970-01-01
  • 2014-11-28
  • 2017-06-16
相关资源
最近更新 更多