2014-10-31 61 views
0

我有一個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(); 

現在,我的問題是,爲什麼會發生這種情況?這種行爲背後的任何理由?

+0

我想這可能是因爲你把它叫做屬性而不是方法。嘗試在方法名稱後添加正常大括號,所以它就像'$ posted_po-> purchased_items() - > all()' – NorthBridge 2014-10-31 03:22:00

回答

2

Eloquent中的關係名稱應該在camelCase中。 Laravel(主要)遵守PSR-1標準,其中規定「方法名稱必須在camelCase中聲明」。儘管如此,與中的下劃線的關係將作爲工作,如果作爲一種方法調用,但作爲動態屬性調用時將失敗,而不會跟蹤()

發生這種情況的原因是因爲當您將關係作爲屬性調用時,Eloquent的__get方法將檢查該屬性是否作爲模型中的屬性或列存在。由於它不存在,它將名稱轉換爲camelCase,然後檢查是否存在具有該名稱的方法。所以它最終會在您的模型中尋找purchasedItems的方法。

+0

正確,這意味着你可以**調用像'snake_cased_relation'這樣的動態屬性,它將起作用以及'camelCased'方法名稱。 – 2014-10-31 09:26:00