简体   繁体   English

Laravel仅返回关系中的最后一项等于要求的记录

[英]Laravel only return records where the last item in a relationship equals requirements

I am working on some reporting for an app that has users and bookings. 我正在为具有用户和预订的应用程序进行一些报告。

The aim is to return all users that haven't made a booking within the last 2 months. 目的是返回过去两个月内未预订的所有用户。

My query currently returns all users who has ever made a booking at the given team and order the bookings by newest to oldest. 我的查询当前返回曾在给定团队进行过预订的所有用户,并按最新到最旧的顺序进行预订。

My question is how can I only return users where the last booking made has an estimated booking time more than 2 months ago? 我的问题是,我如何才能仅回退上次预订的估计预订时间超过2个月的用户?

My current query is: 我当前的查询是:

$collection = User::whereHas('customerBookings', function($q) use ($teamId) {
    $q->where('team_id', $teamId);
})->with(['customerBookings' => function ($q) use ($teamId) {
    $q->where('team_id', $teamId);
    $q->orderBy('estimated_booking_time', 'desc');
}])
->get();

This correctly returns all users that have bookings (relationship to a bookings table) that have the requested team_id and then only return the bookings that match the same requirements. 这将正确返回所有具有所请求team_id的预订(与预订表的关系)的用户,然后仅返回符合相同要求的预订。

I was going to use ->reject on the collection but I would rather just filter out in the query itself. 我本打算在集合上使用-> reject,但我宁愿只是在查询本身中进行过滤。

Ideally I want to add something to the with claus: 理想情况下,我想添加一些内容:

$q->where( FIRST RELATIONSHIP ITEM ->estimated_booking_time, '<=', Carbon::now()->subMonths(2) );

The issue for me is how I can get the first item from the relationship and use it to only return the users depending on this last item. 对我来说,问题是如何从关系中获取第一个项目,并使用它仅取决于最后一个项目来返回用户。

You can just put in where() the time of last booked (eg 2months ago) minus the time now . 您可以只输入where()上次预订的时间(例如2个月前)减去now的时间。 You may also have a look at this reference . 您也可以查看此参考 I think this has similar to yours. 我认为这与您的相似。

Probably you have a has-many relationship between the User and the Booking models. 用户和预订模型之间可能存在很多关系。 The User model does have a "bookings()" method related to the Booking model. 用户模型确实具有与预订模型有关的“ bookings()”方法。

Said that, you can do: 说,您可以执行以下操作:

$users = \App\User::whereHas('bookings', function ($query) {
     $query->where('lestimated_booking_time', '<=', Carbon::now()->subMonths(2));
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM