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

Posted

技术标签:

【中文标题】Laravel Eloquent Eager Loading:加入同一张表两次【英文标题】:Laravel Eloquent Eager Loading : Join same table twice 【发布时间】:2014-03-17 01:29:01 【问题描述】:

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

users table
id
name

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

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

我们可以使用 with() 对 Laravel eloquent 急切加载做同样的事情吗?

我们可以这样做吗:

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?
     
));

谢谢!

【问题讨论】:

【参考方案1】:
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
    

    使用“with”:

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

    有连接:

    $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

【讨论】:

以上是关于Laravel Eloquent Eager Loading:加入同一张表两次的主要内容,如果未能解决你的问题,请参考以下文章

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

关于Eager用Laravel Eloquent Model中的选择过滤器加载

Laravel Eloquent Where and or Where with Eager Load 无法正常工作

Eloquent Eager Load Constraints 返回 JSON String 而不是 Object

通过 Eager Loading 从 Eloquent 获取 RAW SQL 查询

Laravel - Eager Loading BelongsToMany 关系