Support the ongoing development of Laravel.io →
Laravel Database

Ive got an issue with my application when i add paginate to the statement, it comes up with an error about my group by.

This code works (without pagination):

$productsQuery = Product::where('approved', '=', 1)->leftJoin('reviews', 'reviews.products_id', '=', 'products.id')->select('products.*', DB::raw('AVG(ratings) as ratings_average' )) ->groupBy('id') ->orderBy('ratings_average', 'DESC');

This code does not work (trying to paginate):

$productsQuery = Product::where('approved', '=', 1)->leftJoin('reviews', 'reviews.products_id', '=', 'products.id') ->select('products.*', DB::raw('AVG(ratings) as ratings_average' )) ->groupBy('id') ->orderBy('ratings_average', 'DESC') ->paginate(18);

Error:

SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in group statement is ambiguous

The error seems to suggest a problem with a group by but i'm presuming its something to do with paginate, when considering it works without. Has anyone experienced this problem and does anyone know how i work around this and get my query to paginate?

Last updated 3 years ago.
0

try this->paginate($limit, ['products.id']);

It work for me.

0

Sign in to participate in this thread!

PHPverse

Your banner here too?

Ryab Floo Ryab Floo razzo20 Joined 28 Jul 2017

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.

© 2025 Laravel.io - All rights reserved.