So if I understand correctly, an item has many places, and a place has many participants. For this, you can use a HasManyThrough relation on the Item model: http://laravel.com/docs/5.0/eloquent#has-many-through
Adding a subquery to an eloquent query
I want to add a field to the result set of an eloquent query that its value is provided by a subquery.
In other words I want the returned eloquent models have an extra field using that subquery.
SELECT * , (
SELECT COUNT( * )
FROM `items` AS `i`
INNER JOIN `places` ON `places`.`item_id` = `i`.`id`
INNER JOIN `participants` ON `participants`.`place_id` = `places`.`id`
WHERE `items`.`id` = `i`.`id`
AND `participants`.`approved` =1
) AS `unapproved_participants`
FROM `items`
so I have both items fields and the unapproved_participants
@JarekTkaczyk Tnx but eager loading participantsCount results to a collection of the participants plus their count.
I read your blog post and noticed that for counting has many relations you used hasOne to avoid a collection
but i don't think the same is possible with the hasManyThrough.
So I used the other method that you have described in your blog post and joined the tables and at the end using selectRaw() added the all items fields and the count of their unapproved participants.
Thank you for your useful post.
here is the final code:
Item::leftJoin('places', 'items.id', '=', 'places.item_id')
->leftJoin('participants', 'places.id', '=', 'participants.place_id')
->groupBy('items.id')
->selectRaw('items.*, COUNT(IF(approved = 0, 1, NULL)) AS unapproved_participants');
Please or to participate in this conversation.