Skip to content

Commit 704a73a

Browse files
authored
Merge pull request #19 from bretoreta/master
Update package to avoid n+1 query problem and add option to eager load relationships when loading recommendations
2 parents 32d1992 + 4e30718 commit 704a73a

File tree

1 file changed

+19
-9
lines changed

1 file changed

+19
-9
lines changed

src/HasRecommendation.php

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -300,7 +300,7 @@ public static function calculateSimilarityMatrix($models, $config): array
300300
*/
301301
public function getRecommendations($name)
302302
{
303-
$config = self::getRecommendationConfig()[$name] ?? null;
303+
$config = $this->getRecommendationConfig()[$name] ?? null;
304304

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

315-
$return = collect();
316-
317-
foreach ($recommendations as $recommendation) {
318-
$model = app($recommendation->target_type);
319-
$target = $model->where('id', $recommendation->target_id)->first();
320-
321-
$return->push($target);
322-
}
315+
316+
$return = $this->whereIn('id', $recommendations->pluck('target_id'))->get();
323317

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

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

336330
return $return;
337331
}
332+
333+
/**
334+
* Return the list of recommended models with relationships
335+
*
336+
* @param string $name Name of the recommendation set
337+
* @param array $relationships Relationships that should be loaded with the recommendations
338+
*
339+
* @return Collection
340+
*/
341+
public function getRecommendationsWithRelationships($name, $relationships)
342+
{
343+
$models = $this->getRecommendations($name);
344+
$models->load($relationships);
345+
346+
return $models;
347+
}
338348
}

0 commit comments

Comments
 (0)