I am unable to use GROUP_CONCAT for 'one to many relationship' when the query has multiple other joins.
This is the error message:
SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'laravel.profile.id' which is not functionally dependent on columns in GROUP BY clause; this is
The query:
return DB::table('users as u')
->select('u.id','profile.*',DB::raw("group_concat(photos.url_link) as user_images"))
->leftjoin('user_photos as photos', 'u.id', '=', 'photos.id')
->leftjoin('user_profiles as profile', 'u.id', '=', 'profile.user_id')
/*/* ->groupBy('photos.user_id')*/
->groupBy('u.id','profile.user_id')
->where('u.id', $id)
->first();
Table relationships:
User is in 'one to many' relationship with photos
User is in 'one to one' relationship with profile
the query works if i take out the groupBy and the 'group_concat' part of the query:
return DB::table('users as u')
->select('u.id as user_id','profile.*')
->leftjoin('user_photos as photos', 'u.id', '=', 'photos.id')
->leftjoin('user_profiles as profile', 'u.id', '=', 'profile.user_id')
->where('u.id', $id)
->first();
The query also works if I only have one join:
this query works:
return DB::table('users as u')
->select('u.id',DB::raw("group_concat(photos.url_link) as user_images"))
->leftjoin('user_photos as photos', 'u.id', '=', 'photos.id')
->groupBy('u.id')
->where('u.id', $id)
->first();