我使用Laravel口才,我有以下代码:
<?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;
}
?>
我想要达到的是
$lastreport
是预加载的。在这段代码中,查询将被执行太多次(每个批量有1000个模型,导致1000个子查询)。
在普通的SQL中,我可以这样做:
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'
数据库伪代码:
TABLE bulks
id, info
TABLE models
id, bulk_id, info
TABLE reports
id, model_id, message