Laravel getRelations() returns 空白

Laravel getRelations() returns blank

I'm trying to query a relationship for use with an accessor with getNameAttribute this is my code

<?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');
    }
}

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

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

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

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

您想改用 getRelationValue

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

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

getRelationValue 是引入要对其执行聚合函数的相关模型的好方法。计数可以使用 withCount,但对于总和和平均值,getRelationValue 与直接调用相关模型相比,预加载效果更好。