Laravel getRelations() 返回空白

Mig*_*ens 6 php foreign-keys laravel

我正在尝试查询与带有 getNameAttribute 的访问器一起使用的关系,这是我的代码

<?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');
    }
}
Run Code Online (Sandbox Code Playgroud)

但它什么也没返回..我做错了什么吗?谢谢你!

sha*_*ddy 4

当您请求关系时event,该关系尚未加载,这就是您得到空值的原因。如果您想访问event关系,只需执行此操作$this->event,它就会加载它,因此您可以访问它的属性:

public function getNameAttribute() {
    return $this->event->name;
}
Run Code Online (Sandbox Code Playgroud)

getRelation方法会返回一个关系,如果它已经加载到模型中,则不会触发加载。

  • @Notflip是的,它正在触发Eloquent的神奇“__get”方法。你可以查看[文档](http://laravel.com/docs/5.0/eloquent)它有很多很酷的技巧和技巧。 (2认同)