如何使用Eloquent ORM访问第二个表关系?

时间:2018-09-20 06:18:08

标签: php laravel eloquent

所以我有3种型号:

// Customer

public function invoices() {
    return $this->hasMany('App\Invoice');
}

// Invoice

public function payments() {
    return $this->hasMany('App\Payment');
}

// Payment

public function invoice() {
    return $this->belongsTo('App\Invoice');
}

在我的控制器中,我想访问客户的所有发票。

Customer::findOrFail($customer_id)->invoices;

上面的代码运行良好,但是我还想为客户的每张发票附加所有付款。

我尝试做Customer::findOrFail($customer_id)->invoices->payments;,但看来客户模型也在寻找付款方式。

我在这里想念东西吗?

3 个答案:

答案 0 :(得分:3)

$customer = Customer::with(array('invoices','invoices.payments'))->where('customer_id',$customer_id)->get();

答案 1 :(得分:1)

使用:

$customer = Customer::with('invoices.payments')->findOrFail($customer_id);

答案 2 :(得分:1)

$customer = Customer::find($id)->with('invoices.payments')->get();

Eloquent Eager loading doc