我的user模型有名为person_id的外键引用,它引用了people表中的单个person。

当我死了&转储经过身份验证的用户(dd(auth()->user()))时,我得到:
{"id":1,"email":"foo@bar.baz","is_enabled":1,"person_id":3,"created_at":"2017-12-12 10:04:55","updated_at":"2017-12-12 10:04:55","deleted_at":null}我可以通过调用auth()->user()->person来访问person,但是它是一个原始模型。person的演示器不适用于它,因此我不能在auth用户的个人上调用演示者方法,因为我不知道在哪里调用我的演示者。
哪里是调优auth()->user对象及其关系的最佳位置,以便我可以在它们上应用特定的模式?
谢谢,Laravel 5.5.21。
发布于 2018-02-15 12:12:54
使用load()方法:
auth()->user()->load('relationship');发布于 2018-02-15 12:26:34
您可以使用全球范围
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function person()
{
return $this->belongsTo(Person::class);
}
/**
* The "booting" method of the model.
*
* @return void
*/
protected static function boot()
{
parent::boot();
static::addGlobalScope('withPerson', function (Builder $builder) {
$builder->with(['person']);
});
}
}https://stackoverflow.com/questions/48806968
复制相似问题