framework: withCount not working as expected

  • Laravel Version: 8.12.3
  • PHP Version: 7.4
  • Database Driver & Version: Mysql 8

Description:

After upgrading Laravel from 7 to 8 $model->withCount('relation') returns unexpected value because of the limit 1 in Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php file 417 row.

Steps To Reproduce:

  1. Create few models(for example products) with ids(1,2,3,4) with morphMany relation, for example comments
  2. Create comments table with column(id, comment, confirmed_at)
  3. Create 2 comments for all products
  4. For all products except with id 3, add confirmed_at date now date, or some other date
  5. For product with id 3, make all comments confirmed_at column null
  6. Call Products::withCount(['comments'=> fn($q) => $q->whereNotNull('confirmed_at')])

Expected result:

id comments_count
1 2
2 2
3 0
4 2

Result returned:

id comments_count
1 2
2 2
3 0
4 0

After removing ->limit(1) in Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php file 417 row, everything starts working as expected.

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Comments: 15 (11 by maintainers)

Most upvoted comments

Yes, this PR introduces a breaking change I think: https://github.com/laravel/framework/pull/34965. Quick way to verify is that all the tests have been changed to output a different query now. Ping @khalilst