加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

php – Laravel Eloquent Eager Loading:加入同桌两次

发布时间:2020-12-14 19:48:40 所属栏目:大数据 来源:网络整理
导读:我有一个用户表和约会表.在约会表中,我有两个用户ID(customer_id,staff_id).我想检索所有带有客户名称和员工姓名的约会. users tableidnameappointments tableidstaff_id(user_id)customer_id(user_id)datetime 如您所见,我必须使用约会表两次加入users表.
我有一个用户表和约会表.在约会表中,我有两个用户ID(customer_id,staff_id).我想检索所有带有客户名称和员工姓名的约会.
users table
id
name

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

如您所见,我必须使用约会表两次加入users表.
通常我用内连接来做这个.

我们可以使用with()使用Laravel eloquent eager loading来做同样的事情吗?

我们可以这样做:

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)使用“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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读