I use Laravel Eloquent and I have this code:
<?php
$bulk = Bulk::where('id', 'bulkid1');
echo $bulk->info;
foreach($bulk->models as $model) {
  echo $model->info;
  $lastreport = $model->reports()->getQuery()->orderBy('created_at', 'desc')->first();
  echo $lastreport->message;
}    
?>
What I want to achieve is that the $lastreport is preloaded. In this piece of code, the query will be executed too many times (every bulk has 1000 models, resulting in 1000 subqueries).
While in plain sql I could just do:
SELECT * FROM bulk
LEFT JOIN models ON bulk.id = models.bulk_id
LEFT JOIN ( SELECT *, MAX(created_at) AS created_at
   FROM
     reports
   GROUP BY
     model_id )
lastreport ON models.id = lastreport.model_id
WHERE bulk.id = 'bulkid1'
Database pseudocode:
TABLE bulks
 id, info
TABLE models
id, bulk_id, info
TABLE reports
id, model_id, message
 
    