Laravel Eloquent Eager Loading:加入同一张表两次

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21834379/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 09:03:05  来源:igfitidea点击:

Laravel Eloquent Eager Loading : Join same table twice

phpdatabasejoinlaraveleloquent

提问by The Dude

I have a userstable and an appointmentstable. In appointment table I have two user ID's (customer_id, staff_id). I want to retrieve all the appointments with customer name and the staff name.

我有一个用户表和一个约会表。在约会表中,我有两个用户 ID(customer_id、staff_id)。我想检索所有带有客户姓名和员工姓名的约会。

users table
id
name

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

As you can see, I have to join the users table twice with the appointments table. Usually I do this with inner joins.

如您所见,我必须将 users 表与约会表连接两次。通常我用内部连接来做这件事。

Can we do the same thing with Laravel eloquent eager loading using with()?

我们可以使用 with() 对 Laravel 雄辩的预加载做同样的事情吗?

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 final output 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!

谢谢!

回答by Nostalgie

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) With use "with":

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) With joins:

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

About second question - This is for subqueries. Look documentation: http://laravel.com/docs/eloquent#eager-loading

关于第二个问题 - 这是针对子查询的。查看文档:http: //laravel.com/docs/eloquent#eager-loading