Skip to content

Commit 8b84cf5

Browse files
markokeeffeMark O'Keeffetaylorotwell
authored
[7.x] Significant performance issue in Eloquent Collection loadCount() method (#34177)
* Update Eloquent Collection loadCount() to resolve performance issue * Update Collection.php Co-authored-by: Mark O'Keeffe <[email protected]> Co-authored-by: Taylor Otwell <[email protected]>
1 parent af8ac1b commit 8b84cf5

File tree

1 file changed

+6
-7
lines changed

1 file changed

+6
-7
lines changed

src/Illuminate/Database/Eloquent/Collection.php

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -79,19 +79,18 @@ public function loadCount($relations)
7979
->whereKey($this->modelKeys())
8080
->select($this->first()->getKeyName())
8181
->withCount(...func_get_args())
82-
->get();
82+
->get()
83+
->keyBy($this->first()->getKeyName());
8384

8485
$attributes = Arr::except(
8586
array_keys($models->first()->getAttributes()),
8687
$models->first()->getKeyName()
8788
);
8889

89-
$models->each(function ($model) use ($attributes) {
90-
$this->where($this->first()->getKeyName(), $model->getKey())
91-
->each
92-
->forceFill(Arr::only($model->getAttributes(), $attributes))
93-
->each
94-
->syncOriginalAttributes($attributes);
90+
$this->each(function ($model) use ($models, $attributes) {
91+
$extraAttributes = Arr::only($models->get($model->getKey())->getAttributes(), $attributes);
92+
93+
$model->forceFill($extraAttributes)->syncOriginalAttributes($attributes);
9594
});
9695

9796
return $this;

0 commit comments

Comments
 (0)