2014-10-31 34 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