代码之家  ›  专栏  ›  技术社区  ›  wobsoriano

如何使用雄辩的ORM访问第二个表关系?

  •  0
  • wobsoriano  · 技术社区  · 6 年前

    // 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 回复  |  直到 6 年前
        1
  •  3
  •   Sapna Bhayal    6 年前
    $customer = Customer::with(array('invoices','invoices.payments'))->where('customer_id',$customer_id)->get();
    
        2
  •  1
  •   Jinal Somaiya    6 年前

    $customer = Customer::with('invoices.payments')->findOrFail($customer_id);
    
        3
  •  1
  •   Roms    6 年前
    $customer = Customer::find($id)->with('invoices.payments')->get();
    

    Eloquent Eager loading doc

    推荐文章