perf: Allow eager loading posts relations of GET discussion endpoint (#3048)

This commit is contained in:
Sami Mazouz 2021-08-23 20:33:21 +01:00 committed by GitHub
parent 04f7585e03
commit 1e9533a09c
2 changed files with 27 additions and 8 deletions

View File

@ -148,13 +148,9 @@ abstract class AbstractSerializeController implements RequestHandlerInterface
abstract protected function createElement($data, SerializerInterface $serializer);
/**
* Eager loads the required relationships.
*
* @param Collection $models
* @param array $relations
* @return void
* Returns the relations to load added by extenders.
*/
protected function loadRelations(Collection $models, array $relations): void
protected function getRelationsToLoad(): array
{
$addedRelations = [];
@ -164,6 +160,20 @@ abstract class AbstractSerializeController implements RequestHandlerInterface
}
}
return $addedRelations;
}
/**
* Eager loads the required relationships.
*
* @param Collection $models
* @param array $relations
* @return void
*/
protected function loadRelations(Collection $models, array $relations): void
{
$addedRelations = $this->getRelationsToLoad();
if (! empty($addedRelations)) {
usort($addedRelations, function ($a, $b) {
return substr_count($a, '.') - substr_count($b, '.');

View File

@ -187,12 +187,21 @@ class ShowDiscussionController extends AbstractShowController
$query->orderBy('created_at')->skip($offset)->take($limit)->with($include);
$posts = $query->get()->all();
$posts = $query->get();
foreach ($posts as $post) {
$post->discussion = $discussion;
}
return $posts;
$this->loadRelations($posts, $include);
return $posts->all();
}
protected function getRelationsToLoad(): array
{
$addedRelations = parent::getRelationsToLoad();
return $this->getPostRelationships($addedRelations);
}
}