且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Laravel雄辩的渴望加载:两次加入同一张桌子

更新时间:2023-08-28 13:50:58

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