我有一個model
與具有這種命名的關係:Laravel 4個關係與名稱由undescore分離不工作
class PurchaseOrder extends Eloquent implements IModel
{
protected $guarded = ['id'];
protected $table = 'purchase_orders';
// this function has name separated by an _ or underscore
public function purchased_items()
{
return $this->hasMany('PurchasedItem');
}
}
,我使用它訪問:
$posted_po = PurchaseOrder::find($po_id);
$purchased_items = $posted_po->purchased_items->all();
上面的代碼產生錯誤
PHP Fatal error: Call to a member function all() on a non-object
但以某種方式更改關係的名稱lves我的問題:
public function purchasedItems()
{
return $this->hasMany('PurchasedItem');
}
$posted_po = PurchaseOrder::find($po_id);
$purchased_items = $posted_po->purchasedItems->all();
現在,我的問題是,爲什麼會發生這種情況?這種行爲背後的任何理由?
我想這可能是因爲你把它叫做屬性而不是方法。嘗試在方法名稱後添加正常大括號,所以它就像'$ posted_po-> purchased_items() - > all()' – NorthBridge 2014-10-31 03:22:00