Support the ongoing development of Laravel.io →
Database Eloquent
Last updated 1 year ago.
0
DB::table( 'articles' )
	->join( 'ratings', 'ratings.article_id', '=', 'articles.id' )
	->where( 'articles.state', 1 )
	->groupBy( 'articles.id' )
	->select( 'articles.id', DB::raw( 'AVG( ratings.rank )' ) )
	->get();
Last updated 1 year ago.
0

Thanks for your answer, but I would like to stick with Eloquent and not Fluent, as I have 4 relations on my Article model so it's easier to use. But maybe eloquent is not made for that ?

Last updated 1 year ago.
0

The problem is that you need to use group by in order to use avg(), and I believe that there is no way to do queries with Fluent that uses aggregate functions that needs other tables to work.

Last updated 1 year ago.
0

Ok I found the solution, by using Eloquent + Fluent, to be able to use my relationships. This is my code to get a collection of all my Articles + User + Rating average :

$articles = Articles::where('state', '=', '1')
	->with('user')
	->leftJoin('ratings', 'ratings.article_id', '=', 'articles.id')
	->select(array('articles.*',
		DB::raw('AVG(rating) as ratings_average')
		))
	->groupBy('id')
	->orderBy('ratings_average', 'DESC')
	->get();
Last updated 1 year ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

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.