2016-08-04 86 views
0

我有一個表Users這些列:Laravel生子查詢同桌

 $users = User::select(['id','name','level','parent','updated_at']) 
    ->where('level','>',1) 
    ->get(); 

輸出:

 id name  level  parent updated_at 
     ----+---------+-----------+--------+------------- 
     12 Jhon  1   0  2016-02-01 
     99 Carl  2   12  2016-02-01 

然後我嘗試一下本作展列parent如何名稱id例如有關,第二行,顯示Jhon代替12

我想這個代碼...任何幫助閱讀...

 $users = User::select(['id','name','level', 
    DB::raw("SELECT * FROM users WHERE id = users.parent) 
    'updated_at']) 
    ->where('level','>',1) 
    ->get(); 

預期輸出:

 id name  level  parent updated_at 
     ----+---------+-----------+--------+------------- 
     12 Jhon  1     2016-02-01 
     99 Carl  2   Jhon  2016-02-01 

回答

0

你想要一個leftJoin獲取父名:

$users = User::select(['users.id','users.name','users.level', 'parent.name') 
->leftJoin('users AS parent','users.parent','=','parent.id') 
->where('users.level','>',1) 
->get();