Zong
Zong

Reputation: 71

Laravel How to query db with multiple table?

I have a query in mySQL, but i have no idea how to transfer the format to the laravel. This is my query line.

select T.id,t_id,T.name t_name, T.phone t_phone, 
T.address t_address, T.Department t_department,
 bgroup,sgroup,st_id,users.name st_name,
 user_info.phone st_phone, user_info.address st_address,
 user_info.Department st_department,st_hospital,st_code,
 st_art,g_semester from 
 (SELECT user_group.id, t_id, name, phone, address,
 Department, bgroup,sgroup,st_id,st_hospital,st_code,
 st_art,g_semester FROM `user_group` 
 left join user_info on `t_id`  = `school_id`
 left join users on `t_id` =`s_id`) T 
 left join user_info on `st_id`  = `school_id` 
 left join users on `st_id` =`s_id`

Have anyone can help me? How to transfer this query to the laravel format? I dont have any idea how to select from another query?

from (SELECT user_group.id, t_id, name, phone, address, Department, bgroup,sgroup,st_id,st_hospital,st_code, st_art,g_semester FROM user_group left join user_info on t_id = school_id left join users on t_id =s_id) T

Upvotes: 0

Views: 43

Answers (1)

Jonas Staudenmeir
Jonas Staudenmeir

Reputation: 25906

Here's the foundation:

$from = DB::table('user_group')
    ->select('user_group.id', ...)
    ->leftJoin('user_info', 't_id', 'school_id')
    ->leftJoin(...);
DB::query()
    ->select('T.id as t_id', ...)
    ->fromSub($from, 'T')
    ->leftJoin('user_info', 'st_id', 'school_id')
    ->leftJoin(...)
    ->get();

Upvotes: 1

Related Questions