我的user
模型具有名为person_id
的外键引用,引用了person
表中的单个people
。
当我死去的时候转储经过身份验证的用户(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
来访问此人,但它是原始模型。由于我不知道在哪里给我的演示者打电话,因此我无法在auth用户的电话上调用演示者方法。
调整auth()->user
对象及其关系的最佳位置在哪里,以便我可以在其上应用特定模式?
谢谢,
Laravel 5.5.21
。
答案 0 :(得分:4)
使用load()
方法:
auth()->user()->load('relationship');
答案 1 :(得分:3)
您可以使用global scope:
<?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']);
});
}
}