Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

satheeshkumarj's avatar

Grouping error: 7 ERROR: column "companies.name" must appear in the GROUP BY clause or be used in an aggregate function

Error is showing. When I tried to join 3 tables. I have 3 tables, structure is shown below

users(table name)

id | name | gender | email | contact number | user_type | status

user_company (table name)

id | user_id | company_id

companies (table name)

id | name | contact_number | email

When I tried to join these 3 tables.

$empRecords = DB::table('users as u')
                ->select('u.id', 'u.gender', 'u.user_type', 'u.name', 'u.email', 'u.contact_number', 'u.status','companies.name as company_name', DB::raw('count(uc.company_id) as userCompanyCount'))
                ->join('user_company as uc', 'uc.user_id', '=', 'u.id')
                ->join('companies', 'companies.id', '=', 'uc.company_id')
               ->whereIn('u.user_type', array('Admin'))
               ->whereIn('u.status', array(1, 2))
->groupBy('u.id', 'u.gender', 'u.user_type', 'u.name', 'u.email', 'u.contact_number', 'u.status');
				->get();

This showing error Grouping error: 7 ERROR: column "companies.name" must appear in the GROUP BY clause or be used in an aggregate function

When I add

->groupBy('company_name')

results not getting

0 likes
4 replies

Please or to participate in this conversation.