我有一个类似的模型
<?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()
谢谢&关于
Invoice::where(...)
返回一个生成器(Illuminate'Database'Eloquent'Builder
)您想要的是一个模型(Illuminate'Database'Eloquent'Model
),您可以通过在末尾链接->get()
(或first
、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)
而不是where('Id', $id)->first()
会更短、更可读。