Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

349
Views
Select for many to many relation

I would like to understand how should a select according to my scheme look like. Since it's many to many relation, I have used binding table in the scheme. many to many scheme

Now, my app situation is: I want to show all repairs for a vehicle with some id. In my function, I have that id stored in a variable let's say $id so I know what vehicle I want to see all repairs so the table vehicles is not important in this case for this select that I need.

So I want to write a select for specific vehicle where repairs.vehicle_id = $id.

One repair row has to contain columns worker name and surname. Later on, I have a table for parts ready to add into repairs but it will be same scenario like with workers so I just want to understand now, how can I write such select using joins and group by and other necessary sql functions to get workers working on the repair.

Of course, in one repair, there can be more workers. Table repair_worker would look like this:

"repair_id" , "worker_id"
    "86"    ,     "2"
    "87"    ,     "3"
    "87"    ,     "4"
    "88"    ,     "1"
    "88"    ,     "2"

I am using Laravel framework but I would like to use only RAW SQL, no laravel functions if possible.

EDIT:

$repairs = DB::select(DB::raw('
            select r.id repair_id, w.name, w.surname
                from repairs r
                    join repair_worker rw on r.id = rw.repair_id
                    join workers w on w.id = rw.worker_id
                where r.vehicle_id = ?
                group by w.name, w.surname, r.id
'),[$vehicle->id]);
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

If you just want the names of the workers, this should work:

select r.id repair_id, w.Name, w.SurName
from repairs r
join repair_worker rw on r.id = rw.repair_id
join workers w on w.id = rw.worker_id
where r.vehicle_id = $id
group by r.id, w.Name, w.SurName

To put the repair on a single row, with all the workers in a single column, you can do this:

select r.id repair_id, string_agg(w.Name || ' ' || w.SurName, ', ') workers
from repairs r
join repair_worker rw on r.id = rw.repair_id
join workers w on w.id = rw.worker_id
where r.vehicle_id = ?
group by r.id;
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!