Francisunoxx
Francisunoxx

Reputation: 1458

How to use group_concat with groupBy function?

I'm trying to concatenate my users.id using groupBy function. But it throws me an error. Undefined property: stdClass::$id. I think I didn't missed something because I already import use DB; at the top of my file.

Here how I do it in SQL

SELECT D.department_name, GROUP_CONCAT(U.id) user_id FROM users U
INNER JOIN departments D ON D.id = U.department_id group by D.department_name;

Laravel Eloquent:

$departmentRecipient = DB::table('users')->select('departments.department_name', DB::raw('group_concat(users.id)'))
    ->join('departments', 'departments.id', '=', 'users.department_id')
    ->groupBy('departments.department_name')
    ->get();

Upvotes: 0

Views: 36

Answers (1)

aynber
aynber

Reputation: 23001

If you're trying to access the group_contact property, you need to name it. Otherwise, MySQL will name the column with the function name.

DB::raw('group_concat(users.id) AS id')

Upvotes: 1

Related Questions