Skip to content

[7.x] Fix 'loadCount' method to ensure count is set on all models#32740

Merged
taylorotwell merged 1 commit into
laravel:7.xfrom
gdebrauwer:load-count-with-same-models-bug
May 11, 2020
Merged

[7.x] Fix 'loadCount' method to ensure count is set on all models#32740
taylorotwell merged 1 commit into
laravel:7.xfrom
gdebrauwer:load-count-with-same-models-bug

Conversation

@gdebrauwer
Copy link
Copy Markdown
Contributor

If a model is present multiple times in a collection, all models should get the relationship count set, instead of only the first occurence of that model in the collection.

$posts = Post::where('id', 1)->get()->push(Post::where('id', 1)->get());

$posts[0]->comments_count; // is set
$posts[1]->comments_count; // is not set (bug)

I discovered this bug while I was creating PR #32739 that adds loadMorphCount method. That method uses the loadCount method. The temporary collection that calls the loadCount method, can contain duplicates (e.g. 2 comments can morph to the same post)

If a model is present multiple times in a collection, all models should get the count set, instead of only the first occurence of that model in the collection
@gdebrauwer gdebrauwer changed the title [7.x] Fix 'loadCount' method to set count on all models [7.x] Fix 'loadCount' method to ensure count is set on all models May 10, 2020
@taylorotwell taylorotwell merged commit 5ee0e4d into laravel:7.x May 11, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants