简体   繁体   English

Laravel-在一对多关系中获得有条件的最新记录

[英]Laravel - Get last record with condition in one-to-many relationship

I'm working with version 5.5 of Laravel and I have a one-to-many relationship. 我正在使用Laravel 5.5版,并且我与一对多关系。 In the first table (Passengers) I have the passenger register 在第一张桌子(乘客)中,我有乘客登记册

Passengers
id|name
1|Carlos
2|Pedro

In the second table I have the history of entries / exits of these passengers 在第二张表中,我有这些乘客的进出历史

Histories 历史沿革

id|passenger_id|type|created_at
1|1|in|2018-01-16 00:00:00
2|2|in|2018-01-16 01:00:00
3|3|in|2018-01-16 02:00:00
4|1|out|2018-01-16 03:00:00
5|1|in|2018-01-16 04:00:00
6|2|out|2018-01-16 05:00:00
7|3|out|2018-01-16 06:00:00
8|4|in|2018-01-16 07:00:00

What I would like to get is a count of all passengers with a type column being equal to 'in', based on a last interaction of each User, that is, my expected result would be this 我想得到的是根据每个用户的最后一次交互,对所有类型列等于“ in”的乘客进行计数,也就是说,我的预期结果是

id|passenger_id|type|created_at
5|1|in|2018-01-16 04:00:00
8|4|in|2018-01-16 07:00:00

count = 2 rows

Researching I was able to get to a SQL Query that caters to me, but I do not know how to apply it using Laravel 经过研究,我能够找到适合我的SQL查询,但是我不知道如何使用Laravel应用它

SELECT p.id, p.name, h1.id, h1.created_at, h1.type
FROM passengers p
JOIN histories h1 ON (p.id = h1.passenger_id)
LEFT OUTER JOIN histories h2 ON (p.id = h2.passenger_id AND (h1.created_at < h2.created_at OR h1.created_at = h2.created_at AND h1.id < h2.id))
WHERE h2.id IS NULL AND h1.type='in';

Can someone help me mount this query in Laravel or if I have another simple solution I appreciate 有人可以帮我在Laravel中安装此查询吗,或者如果我有另一个简单的解决方案,我将不胜感激

With the help of @edersoares, I found the solution, it will be registered if anyone has the same problem 在@edersoares的帮助下,我找到了解决方案,如果有人遇到同样的问题,它将被注册

$subquery = History::query()->selectRaw('MAX(id)')->groupBy('passenger_id');
$query = History::query()->whereIn('id', $subquery)->where('type', 'in');
$passengersIn = $query->get();

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

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