关系方法必须通过 Laravel 4 中的非视图从模型调用返回一个 Illuminate\Database\Eloquent\Relations\Relation 类型的对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20731849/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation from model call by not view in Laravel 4
提问by kaimerra
I have a model, Ability, which belongs to another model AbilityType.
我有一个模型,能力,属于另一个模型能力类型。
<?php
class Ability extends Eloquent {
public function abilityType() {
return $this->belongsTo('AbilityType');
}
public function name() {
return $this->abilityType->name;
}
}
I can make this call in my blade template successfully:
我可以在我的刀片模板中成功进行此调用:
$ability->abilityType->name
But when I make that same call in my Ability model, it throws an exception:
但是当我在我的能力模型中进行同样的调用时,它会抛出一个异常:
ErrorException Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation
Do the dynamic properties differ in behavior between view and model layer? What am I missing here?
动态属性在视图层和模型层之间的行为是否不同?我在这里错过了什么?
回答by Joseph Silber
Laravel uses a special getFooAttribute
syntax to load dynamic properties:
Laravel 使用一种特殊的getFooAttribute
语法来加载动态属性:
class Ability extends Eloquent {
public function abilityType ()
{
return $this->belongsTo('AbilityType');
}
public function getNameAttribute ()
{
return $this->abilityType->name;
}
}