【问题标题】:Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation from model call by not view in Laravel 4关系方法必须从模型调用中返回类型为 Illuminate\Database\Eloquent\Relations\Relation 的对象,而不是在 Laravel 4 中查看
【发布时间】:2013-12-22 17:10:03
【问题描述】:

我有一个模型,Ability,它属于另一个模型 AbilityType。

    <?php
class Ability extends Eloquent {

    public function abilityType() {
        return $this->belongsTo('AbilityType');
    }

    public function name() {
        return $this->abilityType->name;
    }
}

我可以在刀片模板中成功调用:

$ability->abilityType->name

但是当我在我的能力模型中进行相同的调用时,它会引发异常:

ErrorException Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation

动态属性在视图层和模型层之间的行为是否不同?我在这里错过了什么?

【问题讨论】:

  • 您能否展示代码如何从模型内部/模型上调用abilityType?应该只是:$this-&gt;abilityType-&gt;name 或即在控制器中Ability::find(1)-&gt;abilityType-&gt;name

标签: php laravel laravel-4 eloquent


【解决方案1】:

Laravel 使用特殊的 getFooAttribute 语法来加载动态属性:

class Ability extends Eloquent {

    public function abilityType ()
    {
        return $this->belongsTo('AbilityType');
    }

    public function getNameAttribute ()
    {
        return $this->abilityType->name;
    }

}

【讨论】:

    猜你喜欢
    • 2018-03-20
    • 2014-07-09
    • 2014-06-26
    • 1970-01-01
    • 2017-12-21
    • 2018-04-24
    • 1970-01-01
    • 2015-02-26
    相关资源
    最近更新 更多