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
方法将返回给你一个关系,如果它已经加载到模型中,它不会触发加载。
关于php - Laravel getRelations() 返回空白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30525259/