title: Laravel 5.1 Eloquent with() and max() using multiple has-many relationships
body: <p>I'm trying to use Eloquent to find the max value of a column on the last table of a multiple has-many relationship.</p>
  
  <p>Given the following table structure.</p>
  
  <p>Buildings</p>
  
  <pre><code>+----+---------------+
  | id | building_name |
  +----+---------------+
  |  1 | Building 1    |
  |  2 | Building 2    |
  +----+---------------+
  </code></pre>
  
  <p>Rooms</p>
  
  <pre><code>+----+-----------+-------------+
  | id | room_name | building_id |
  +----+-----------+-------------+
  |  1 | Room 1    |           1 |
  |  2 | Room 2    |           1 |
  |  3 | Room 3    |           2 |
  +----+-----------+-------------+
  </code></pre>
  
  <p>maintenancelog</p>
  
  <pre><code>+----+-------------------+---------+---------------------+
  | 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 |
  +----+-------------------+---------+---------------------+
  </code></pre>
  
  <p>I'd like to see if it's possible to generate an eloquent statement that would retrieve the building name, room name, and ONLY the LAST maintenance log date value.</p>
  
  <p>The following works to give me a collection of ALL the values.</p>
  
  <pre><code>$buildings = Building::with('rooms.maintenancelog')-&gt;get();
  </code></pre>
  
  <p>but this errors out, and it looks like it's trying to call max(maintenancelog.timestamp) on the buildings table..</p>
  
  <pre><code>$buildings = Building::with('rooms.maintenancelog')-&gt;max('maintenancelog.timestamp')-&gt;get();
  </code></pre>
  
  <p>Error returned:</p>
  
  <pre><code>.....(SQL: select max(`maintenancelog`.`timestamp`) as aggregate from `buildings`)
  </code></pre>
  
  <p>Am I just asking too much from eloquent, and should I just use the basic query builder</p>