2015-05-29 251 views
2

我想查询使用与访问者与 getNameAttribute的关系,这是我的代码Laravel getRelations()返回空白

<?php namespace App; 

use Illuminate\Database\Eloquent\Model; 

class Conference extends Model{ 

    public function getNameAttribute() { 
     return $this->getRelation('event')->name; 
    } 

    public function event() { 
     return $this->belongsTo('App\Event'); 
    } 

    public function speakers() { 
     return $this->hasMany('App\Speaker'); 
    } 
} 

但它returnin什么..我是不是错误? 谢谢!

回答

2

当您请求关系event时,此关系尚未加载,这就是为什么您会获得空值。如果您要访问的event关系只是这样做$this->event将加载它,这样你就可以访问它的属性:

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

getRelation方法将返回给你的关系,如果它是在模型已经加载,它将不会触发加载。

+0

哦,哇,这很容易,它如何获得该事件?通过雄辩的ORM? – Notflip

+2

@Notflip是的,它触发了雄辩的魔法'__get'方法。你可以查看[文档](http://laravel.com/docs/5.0/eloquent)它有很多很酷的技巧和提示。 – shaddy

+0

这更容易,然后我无法想象!谢谢 – Notflip

1

您想改为使用getRelationValue

public function getNameAttribute() { 
    return $this->getRelationValue('event')->name; 
} 

如果尚未加载关系,则此方法将加载该关系。