Home > Mobile >  Join multiple SQL tables in Laravel
Join multiple SQL tables in Laravel

Time:05-02

I'm stuck trying to join multiple tables together. I have a user table with the users' names and three other tables for patients, doctors, and appointments. The appointment table has the patient's and doctor's id. I can only join two tables, for example, the appointments and the patient, to show the patients' data like the following.

$data = User::join('appointments','users.id','=','appointments.user_id')

I want to know how to do this for the patient and doctor simultaneously. The users' table in DB has a name, last name, phone number, and role id(1 for doctor, 3 for patient). The appointment table has user_id, doctor_id, date, and time. I want to get the user name and the doctor's name.

CodePudding user response:

Try this code Example:

$user = DB::table('user')
        ->leftJoin('posts', 'users.id', '=', 'posts.user_id')
        ->join('orders', 'users.id', '=', 'orders.user_id')
        ->where('posts.title', 'Example')
        ->get();

Laravel Query Builder

CodePudding user response:

Try this:

return $user = User::leftJoin('posts', 'posts.user_id', '=', 'users.id')
                    ->leftJoin('orders','orders.user_id',  '=', 'users.id')
                    ->leftJoin('appointments','appointments.user_id', '=', 'users.id')
                    ->get();

Laravel Query Builder

  • Related