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:
- Create few models(for example
products) with ids(1,2,3,4) with morphMany relation, for examplecomments - Create
commentstable with column(id,comment,confirmed_at) - Create 2 comments for all products
- For all products except with id 3, add
confirmed_atdate now date, or some other date - For product with id 3, make all comments
confirmed_atcolumnnull - 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)
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