Support the ongoing development of Laravel.io →
Database Eloquent
Last updated 2 years ago.
0

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.

Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Leif0 leif0 Joined 6 Sep 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.