V
V
vlad_lutsky2018-07-25 17:02:20
Laravel
vlad_lutsky, 2018-07-25 17:02:20

How to correctly form a query to the db in laravel?

There are three tables - users, images, user groups. The essence of the request is to select all user data from 1 user group and attach all attached images to them:

<?php 
Route::get('/get/database/girls', function () {
  $users = DB::table('users')
    ->join('users_groups', function ($join_groups) {
        $join_groups->on('users.id', '=', 'users_groups.user_id');
    })
    ->join('system_files', function ($join_images) {
        $join_images->on('users.id', '=', 'system_files.attachment_id');
    })
    ->where('users_groups.user_group_id', '=', 1)
    ->get();
  return json_encode($users);
});

queries display several objects
User 1 - name 1 - image 1
User 1 - name 1 - image 2
User 2 - name 1 - image 1
in the system_files table there is a field field that takes values ​​from photo1, photo2, photo3, photo4, photo5, photo6 ( supposedly need to group by it)
How would I group the first two objects so that it is:
User 1 - name 1 - image 1 - image 2
User 2 - name 1 - image 1

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
nozzy, 2018-07-25
@vlad_lutsky

$users = DB::select(
"select
t1.id,
t1.user_name,
GROUP_CONCAT( t3.field SEPARATOR ',') as images
from users t1
join users_groups t2 on t2.user_id = t1.id
join system_files t3 on t3.user_id = t1.id
where t2.user_group_id = 1
group by t1.id, t1.user_name");
return json_encode($users);

M
miki131, 2018-07-25
@miki131

$gid = 1;
User::query()
->whereHas('groups', function($q) use ($gid) {
    $q->where('id', $gid);
})
->with('files')
->get();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question