本文介绍了关系方法必须从模型调用中返回一个类型为Illuminate\Database\Eloquent\Relations\Relation的对象,而不是在Laravel 4中查看的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型,能力,属于另一个模型的能力类型。

 <?php 
class能力扩展Eloquent {

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

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

我可以在我的刀片模板中成功进行此调用:

  $ ability-> capabilitiesType-> name 

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

  ErrorException关系方法必须返回一个对象类型Illuminate\Database\Eloquent\Relations\Relation 

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

解决方案

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

  class能力扩展Eloquent {

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

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

}


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?

解决方案

Laravel uses a special getFooAttribute syntax to load dynamic properties:

class Ability extends Eloquent {

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

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

}

这篇关于关系方法必须从模型调用中返回一个类型为Illuminate\Database\Eloquent\Relations\Relation的对象,而不是在Laravel 4中查看的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 18:04