Laravel eloquent结合max()和where()或有()

问题描述 投票:0回答:1

我正在寻找一个雄辩的声明,它会给出每个room_id的最大值(时间戳),因为该room_id的所有时间戳值都超过了15天。 (基本上任何在过去15天内没有清理的房间......)

maintenancelog

+----+-------------------+---------+---------------------+
| id | maintenance_value | room_id |      timestamp      |
+----+-------------------+---------+---------------------+
|  1 | Cleaned           |       1 | 2015-09-06 00:54:59 |
|  2 | Cleaned           |       1 | 2015-09-07 01:55:59 |
|  3 | Cleaned           |       2 | 2015-09-06 02:56:59 |
|  4 | Cleaned           |       2 | 2015-09-16 03:57:59 |
|  5 | Cleaned           |       3 | 2015-09-06 04:58:59 |
|  6 | Cleaned           |       3 | 2015-09-07 05:59:59 |
+----+-------------------+---------+---------------------+

我很讨厌MySQL,但这相当于一个Oracle声明...

select room_id,max(timestamp) from maintenancelog
group by room_id
having max(timestamp) < sysdate - 15;

雄辩的陈述应该基本上返回以下内容。

1, 2015-09-07 01:55:59
3, 2015-09-07 05:59:59 

我试过了...

$dt = Carbon::now();
$checkdate = $dt->subDays(15);
return $this->groupBy('room_id')->max('timestamp')->having('timestamp','<',$checkdate);

但得到

Call to a member function having() on string

试...

return $this->groupBy('room_id')->havingRaw("max(timestamp)<sysdate()-15");

只返回时间戳超过15的任何行,忽略其他最大值...

php mysql laravel eloquent
1个回答
2
投票

像count()这样的max()是eloquent中的最终函数,代替get()。你真正想要的是select中的max()作为原始语句。

return $this->select(DB::raw('room_id, max(`timestamp`) as `timestamp`'))
    ->groupBy('room_id')
    ->having('timestamp','<',$checkdate)
    ->get();
© www.soinside.com 2019 - 2024. All rights reserved.