2014-02-17 173 views
6

我有一個用戶表和約會表。在預約表中,我有兩個用戶ID(customer_id,staff_id)。我想用客戶名稱和員工姓名檢索所有約會。Laravel Eloquent渴望加載中:加入同一表格兩次

users table 
id 
name 

appointments table 
id 
staff_id(user_id) 
customer_id(user_id) 
datetime 

正如你所看到的,我必須用約會表兩次加入users表。 通常我會這樣做內連接

我們可以用Laravel雄辯地用()來加載嗎?

我們可以這樣做:

appointments::with('users' *)->get();? 
* Do something here to inner join users table twice, and read user1.name as staff_name, user2.name as customer_name. 

這是最後的輸出我需要:

appointment_id 
staff_id 
staff_name 
customer_id 
customer_name 
datetime 

我還有一個問題,什麼是在下面的查詢第二個參數?

User::with(array(
    'post'=> function() use $region { 
      //what is use $region means? Can you give me an example? 
    } 
)); 

謝謝!

回答

10
class T1 extends Eloquent { 

    protected $table = 't1'; 


} 

class T2 extends Eloquent { 

    protected $table = 't2'; 

    public function customer() 
    { 
     return $this->belongsTo('T1','c_id');//c_id - customer id 
    } 
    public function staff() 
    { 
     return $this->belongsTo('T1','s_id');//s_id - staff id 
    } 
} 

1)利用 「與」:

$list = \T2::with('customer')->with('staff')->get(); 
    foreach ($list as $row) { 
     echo 'ID: '.$row->id.', customer: '.$row->customer->name.', staff: '.$row->staff->name.'<br>'; 
    } 

2)隨着加入:

$list = \T2::leftJoin('t1 as customer_table', 'customer_table.id','=','t2.c_id') 
     ->leftJoin('t1 as staff_table', 'staff_table.id','=','t2.s_id') 
     ->select('staff_table.name as staff_name','customer_table.name as customer_name') 
     ->get(); 
foreach ($list as $row) { 
    echo 'customer: '.$row->customer_name.', staff: '.$row->staff_name.'<br>'; 
} 

關於第二個問題 - 這是一個子查詢。 Look documentation:http://laravel.com/docs/eloquent#eager-loading