gpt4 book ai didi

php - Laravel 5.1 Eloquent with() 和 max() 使用多重关系

转载 作者:行者123 更新时间:2023-11-29 01:54:36 25 4
gpt4 key购买 nike

我正在尝试使用 Eloquent 查找多对多关系的最后一个表中列的最大值。

给定以下表结构。

建筑物

+----+---------------+
| id | building_name |
+----+---------------+
| 1 | Building 1 |
| 2 | Building 2 |
+----+---------------+

房间

+----+-----------+-------------+
| id | room_name | building_id |
+----+-----------+-------------+
| 1 | Room 1 | 1 |
| 2 | Room 2 | 1 |
| 3 | Room 3 | 2 |
+----+-----------+-------------+

维护日志

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

我想看看是否可以生成一个 Eloquent 语句来检索建筑物名称、房间名称以及仅最后一次维护日志日期值。

以下工作为我提供了所有值的集合。

$buildings = Building::with('rooms.maintenancelog')->get();

但这会出错,看起来它正试图在建筑物表上调用 max(maintenancelog.timestamp)..

$buildings = Building::with('rooms.maintenancelog')->max('maintenancelog.timestamp')->get();

返回错误:

.....(SQL: select max(`maintenancelog`.`timestamp`) as aggregate from `buildings`)

我是不是对 Eloquent 要求太多了,我应该只使用基本的查询构建器

最佳答案

将以下关系添加到 Rooms 模型...

public function latestMaintenance()
{
return $this->hasOne('App\Maintenancelog')->latest();
}

并将 Eloquent 语句更改为..

$buildings = Building::with('rooms.latestMaintenance')->get();

引用Getting just the latest value on a joined table with Eloquent

关于php - Laravel 5.1 Eloquent with() 和 max() 使用多重关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32675160/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com