$tagsResult
にインデックスを付ける場合 postId
による 、FETCH_GROUP
を使用して実行できます 、次に、内側のネストされたループを削除し、特定のpostIdを持つすべてのタグを一定時間で取得できます:
$sql = "
SELECT pt.idPost, — select idPost first so it’s grouped by this col
t.*
FROM tags t JOIN poststags pt ON t.id=pt.idTag
WHERE pt.idPost IN (array of post ids)
";
$stmt=$db->prepare($sql);
$stmt->execute();
$tagsResult = $smt->fetchAll(\PDO::FETCH_GROUP|\PDO::FETCH_OBJ);
//$tagsResult is now grouped by postId
//see https://stackoverflow.com/questions/5361716/is-there-a-way-to-fetch-associative-array-grouped-by-the-values-of-a-specified-c
foreach($postsResult as &$post) {
if(isset($tagsResult[$post->id])) {
$post->tags = $tagsResult[$post->id];
}
else {
$post->tags = array();
}
}