From b90ca42e870efe14398c8cb8535f08e9dbee2aba Mon Sep 17 00:00:00 2001 From: Oliver Davies Date: Wed, 7 Oct 2020 08:52:18 +0100 Subject: [PATCH] Refactor to use an entity query Refactor from using `loadByProperties` to using an entity query. `loadByProperties` doesn't allow for passing multiple values for a single property such as multiple tags to compare against, and also means that removing the current node can be done in the query rather than filtering it out of the Collection. This might also be a more performant solution if we can do the grouping and sorting of the results in the query rather than needing to perform additional steps on the result. References #3 --- .../src/Repository/RelatedPostsRepository.php | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/web/modules/custom/blog/src/Repository/RelatedPostsRepository.php b/web/modules/custom/blog/src/Repository/RelatedPostsRepository.php index 3051ba6..c59e560 100644 --- a/web/modules/custom/blog/src/Repository/RelatedPostsRepository.php +++ b/web/modules/custom/blog/src/Repository/RelatedPostsRepository.php @@ -20,13 +20,17 @@ final class RelatedPostsRepository { } public function getFor(Post $post): Collection { - $posts = $this->nodeStorage->loadByProperties([ - 'type' => 'post', - ]); + $query = $this->nodeStorage->getQuery(); - return (new Collection($posts)) - ->filter(fn(Post $relatedPost) => $relatedPost->id() != $post->id()) - ->values(); + // Ensure that the current node ID is not returned as a related post. + $query->condition('nid', $post->id(), '!='); + + /** @var array $postIds */ + $postIds = $query->execute(); + + $posts = $this->nodeStorage->loadMultiple($postIds); + + return (new Collection($posts))->values(); } }