如何在Laravel5中调用具有一对多关系的模型

时间:2015-11-06 11:37:01

标签: php laravel-5

我有这样的模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Invoice extends Model
{
    //
     protected $table = 'event_invoice';

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

    public function comments(){
        return $this->hasMany('App\comments','invoiceid');
    }
}

现在,如果我想获得包含所有付款和评论的发票,我应该如何编写电话

我确实喜欢这个

         $invoice = Invoice::where('Id','=',$id)->payments()->comments()->get();

抛出错误

Call to undefined method Illuminate\Database\Query\Builder::payments()

谢谢&amp;问候

1 个答案:

答案 0 :(得分:1)

Invoice::where(...)会返回一个构建器(Illuminate\Database\Eloquent\Builder)。 您想要的是一个模型(Illuminate\Database\Eloquent\Model),您可以通过链接->get()(或first,{{1}来获取该模型最后的方法,如paginate。只有使用此模型,您才能呼吁建立关系。

Invoice::where(...)->get()

顺便说一下,使用Invoice::where('Id', $id)->first()->payments(); // <- This is a *query builder* for payments of that invoice Invoice::where('Id', $id)->first()->payments; // <- This is the collection (array) of payments of that invoice 代替find($id)更短,更易读。