我试图使用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 |
+----+-----------+-------------+
maintenancelog
+----+-------------------+---------+---------------------+
| 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 |
+----+-------------------+---------+---------------------+
我想知道是否可以生成一个能够检索建筑物名称,房间名称以及最后维护日志日期值的雄辩语句。
以下工作可以为我提供所有值的集合。
$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`)
我只是从口才中提出太多要求,我应该只使用基本查询构建器
答案 0 :(得分:3)
将以下关系添加到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