Laravel Eloquent Eager Loading: enter the same table twice

I have a user table and a meeting table. In the destination table, I have two user IDs (customer_id, staff_id). I want to get all appointments with the name of the client and the name of the staff.

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

As you can see, I need to join the user table with the appointment table twice. I usually do this with internal joins .

Is it possible to do the same with the eloquent loading of Laravel with ()?

Can we do something like:

 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. 

This is the end result I need:

 appointment_id staff_id staff_name customer_id customer_name datetime 

I have another question, what is the second parameter in the following query?

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

Thanks!

+6
source share
1 answer
 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) Using "c":

  $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) With associations:

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

About the second question - this is for subqueries. See the documentation: http://laravel.com/docs/eloquent#eager-loading

+10
source

All Articles