【问题标题】:Laravel 5.1 Eloquent with() and max() using multiple has-many relationshipsLaravel 5.1 Eloquent with() 和 max() 使用多个 has-many 关系
【发布时间】:2015-09-20 02:32:00
【问题描述】:

我正在尝试使用 Eloquent 来查找多重 has-many 关系的最后一个表上的列的最大值。

给定以下表格结构。

建筑物

+----+---------------+
| 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 |
+----+-------------------+---------+---------------------+

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

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

$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 要求太多了,我应该只使用基本的查询生成器

【问题讨论】:

    标签: php mysql laravel-5 eloquent


    【解决方案1】:

    将以下关系添加到 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-20
      • 1970-01-01
      • 1970-01-01
      • 2019-11-24
      • 2018-01-03
      • 1970-01-01
      • 2015-12-10
      • 2016-02-11
      相关资源
      最近更新 更多