Laravel雄辩的渴望加载:两次加入同一张桌子 [英] Laravel Eloquent Eager Loading : Join same table twice

查看:47
本文介绍了Laravel雄辩的渴望加载:两次加入同一张桌子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a users table and an appointments table. 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.

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.

我们可以使用with()对Laravel雄心勃勃的渴望加载做同样的事情吗?

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

我们可以做点什么像:

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

谢谢!

推荐答案

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一起使用:

1) With use "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>';
    }

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

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

这篇关于Laravel雄辩的渴望加载:两次加入同一张桌子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆