Skip to content

Commit

Permalink
Merge pull request #19 from bretoreta/master
Browse files Browse the repository at this point in the history
Update package to avoid n+1 query problem and add option to eager load relationships when loading recommendations
  • Loading branch information
umutphp committed Aug 15, 2023
2 parents 32d1992 + 4e30718 commit 704a73a
Showing 1 changed file with 19 additions and 9 deletions.
28 changes: 19 additions & 9 deletions src/HasRecommendation.php
Original file line number Diff line number Diff line change
Expand Up @@ -300,7 +300,7 @@ public static function calculateSimilarityMatrix($models, $config): array
*/
public function getRecommendations($name)
{
$config = self::getRecommendationConfig()[$name] ?? null;
$config = $this->getRecommendationConfig()[$name] ?? null;

if ($config === null) {
return [];
Expand All @@ -312,14 +312,8 @@ public function getRecommendations($name)
->where('source_id', $this->id)
->get();

$return = collect();

foreach ($recommendations as $recommendation) {
$model = app($recommendation->target_type);
$target = $model->where('id', $recommendation->target_id)->first();

$return->push($target);
}

$return = $this->whereIn('id', $recommendations->pluck('target_id'))->get();

$order = $config['recommendation_order'] ?? config('laravel_model_recommendation.recommendation_count');

Expand All @@ -335,4 +329,20 @@ public function getRecommendations($name)

return $return;
}

/**
* Return the list of recommended models with relationships
*
* @param string $name Name of the recommendation set
* @param array $relationships Relationships that should be loaded with the recommendations
*
* @return Collection
*/
public function getRecommendationsWithRelationships($name, $relationships)
{
$models = $this->getRecommendations($name);
$models->load($relationships);

return $models;
}
}

0 comments on commit 704a73a

Please sign in to comment.