Laravel如何使用多个表查询db?

时间:2018-04-19 01:05:29

标签: sql laravel

我在mySQL中有一个查询,但我不知道如何将格式转移到laravel。这是我的查询热线。

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`

有人可以帮助我吗?如何将此查询转换为laravel格式? 我不知道如何从另一个查询中选择?

  

这    (SELECT user_group.id,t_id,姓名,电话,地址,    部门,bgroup,sgroup,st_id,st_hospital,st_code,    st_art,g_semester FROM user_group    在t_id = school_id上左加入user_info    在t_id = s_id)T

上离开加入用户

1 个答案:

答案 0 :(得分:1)

这是基础:

$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();