I don't think you'll be able to do this (efficiently) via Eloquent. Take a look at the query that Eloquent uses for when you fetch Projects using has('likes'):
select
*
from
`projects`
where
(
select
count(*)
from
`users`
inner join
`like_project` on `users`.`id` = `like_project`.`user_id`
where
`like_project`.`project_id` = `projects`.`id`
) >= 1
That obviously doesn't return any information about the number of relations. The simplest way to get that is to do a join:
Project::select('projects.id', DB::raw('COUNT(projects.id) AS number_of_likes'))
->join('like_project', 'id', '=', 'project_id')
->groupBy('projects.id')
->orderBy('number_of_likes', 'desc')
->get();
You could keep things neat and tidy by putting that into a scope. And obviously you'd have to modify that a bit to pull in other columns from projects
or like_project
.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community