Added comment preloading

This commit is contained in:
Marcin Kurczewski 2014-02-24 14:42:38 +01:00
parent 3a2a686b6c
commit ff8bb761ee
2 changed files with 42 additions and 0 deletions

View file

@ -18,6 +18,7 @@ class CommentController
$postCount = PostSearchService::getEntityCount($searchQuery);
$pageCount = ceil($postCount / $commentsPerPage);
PostModel::preloadTags($posts);
PostModel::preloadComments($posts);
$comments = [];
foreach ($posts as $post)
$comments = array_merge($comments, $post->getComments());

View file

@ -174,6 +174,47 @@ class PostModel extends AbstractCrudModel
public static function preloadComments($posts)
{
if (empty($posts))
return;
$postMap = [];
$tagsMap = [];
foreach ($posts as $post)
{
$postId = $post->id;
$postMap[$postId] = $post;
$commentMap[$postId] = [];
}
$postIds = array_unique(array_keys($postMap));
$stmt = new SqlSelectStatement();
$stmt->setTable('comment');
$stmt->addColumn('comment.*');
$stmt->addColumn('post_id');
$stmt->setCriterion(SqlInOperator::fromArray('post_id', SqlBinding::fromArray($postIds)));
$rows = Database::fetchAll($stmt);
foreach ($rows as $row)
{
if (isset($comments[$row['id']]))
continue;
unset($row['post_id']);
$comment = CommentModel::convertRow($row);
$comments[$row['id']] = $comment;
}
foreach ($rows as $row)
{
$postId = $row['post_id'];
$commentMap[$postId] []= $comments[$row['id']];
}
foreach ($commentMap as $postId => $comments)
$postMap[$postId]->setCache('comments', $comments);
}
public static function preloadTags($posts)
{
if (empty($posts))