簡體   English   中英

Laravel Eloquent Eager Loading:兩次加入同一張表

[英]Laravel Eloquent Eager Loading : Join same table twice

我有一個用戶表和一個約會表。 在約會表中,我有兩個用戶 ID(customer_id、staff_id)。 我想檢索所有帶有客戶姓名和員工姓名的約會。

users table
id
name

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

如您所見,我必須將 users 表與約會表連接兩次。 通常我用內部連接來做這件事。

我們可以使用 with() 對 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?
     }
));

謝謝!

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>'; }

關於第二個問題 - 這是針對子查詢的。 查看文檔: http : //laravel.com/docs/eloquent#eager-loading

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM