2017-10-10 32 views
0

我想加入department d表,其中department dl表和user u表。我在SQL查詢中完成了這項工作。laravel - 三個表的內部聯接查詢

SELECT distinct(dl.head), 
     u.user_name, 
     u.id 
from department d 
inner join department dl on d.parent_department_string_id=dl.string_id 
inner join users u on dl.head=u.user_name 
where d.sl_flag=1 

我想在Laravel查詢中做同樣的事情。是否可以使用Laravel中的連接加入同一個表?

回答

0

你可以嘗試這樣的事情。

$departmentData = DB::table('department AS d') 
      ->innerJoin('department AS d1', function($join) { 
       $join->on('d.parent_department_string_id', '=', 'd1.string_id'); 
      }) 
      ->innerJoin('users AS u', function($userJoin) { 
       $userJoin->on('d1.head', '=', 'u.user_name'); 
      }) 
      ->where('d.sl_flag', '=', 1) 
      ->select(\DB::raw('distinct(dl.head) AS head'), 'u.user_name', 'u.id') 
      ->get();