Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

alielkhateeb's avatar

Fetching objects with count of a related object.

Based on the Docs of Counting related models I understand how to count the direct related Models, but how about this case, I have 3 tables, issues, rooms and feedbacks

rooms table has issue_id feedbacks table has room_id

What I want to do is fetch all issues and have a flag like has_feedback with this database structure, What is the best practice of doing so?

Note that an issue can have many rooms, and a room may have many feedbacks

0 likes
5 replies
Mandrizzy's avatar

why do you have a feedback table separate from the issue table ? Can't the issue table have a feedback column that would be populated whether there is a feedback for the corresponding issue.

alielkhateeb's avatar

@Mandrizzy an issue might have more than 1 feedback

You are suggesting to have a has_feedback column in issue table?

That means everytime I am inserting a feedback I will have to update the issue to raise the flag if it was not raised before, if you think this is the best way to handle it can you please elaborate more why is it the best way? Thanks

Mandrizzy's avatar

yes i do think the issue table should have a feedback column and on a the issue model you can say a issue has many feedback that way you can get all the feedback for a particular issue using laravel eloquent this is believe is a much easier approach for example the issue table will have say:



id         issue_name                             feedback
1              fix sink                             please fix sink fast
2              bed-fix                       bed sheet needs wash
3            some issue                       some feedback
2               bed fix                bed sheets still have not been wash 

you can add a constraint on your db saying that a id issue name and feedback be unique in order not to have a duplicate entry

djay's avatar

Hi @alielkhateeb

  • First, decide & finalize about the relationship between the models, that suits your application the best
  • Here is the documentation about relationships
  • test the application
  • Then you can use 2 functions count() and withCount('relationName') - to get count of no. of models
alielkhateeb's avatar

@Mandrizzy Sorry you still don't get my point, a feedback is actually a customer feedback, an issue can have multiple feedbacks, with this structure you are telling me to use an issue will have only one feedback.

@djay I read the documentation, count and withCount will get me count for a direct relationship, for example an issue has many rooms, but each room has many feedbacks I wanna get the count of feedbacks per issue.

a greedy way is to loop on all rooms of an issue and get the feedbacks per room, but I was thinking that there is a better way

Please or to participate in this conversation.