Skip to content
Advertisement

Laravel Eloquent to join table and count related

How do I use join with Eloquent taking in consideration the following table structure:

I have a properies table

than I have rooms

here Property is the foreign key than I want to get all Properties and count how many rooms do they have each

The query which retrives all looks like

How do I extend this query to get the desired result?

Advertisement

Answer

This is more of a MySQL join+group+select trick which includes following steps.

  1. Join your relation table(use join if you want to exclude rows with RoomsCount=0, else use leftJoin)
  2. Use groupBy by primaryKey to avoid duplicates of the join.
  3. Select count of joined table
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement