我有一个数据库表来存储我的职位,以免重复它们,并且 Job 模型在内部有关系,所以当我使用 Eloquent 模型时,我必须总是一遍又一遍地调用或加载 JobTitles 模型。有没有办法始终使用内部预加载 JobTitles 的 Job 模型?
class Job extends Model
{
use Notifiable;
protected $fillable = [ ... ];
protected $hidden = [
'token',
];
public function title()
{
return $this->belongsTo('App\Models\JobTitle','job_title_id');
}
public function people()
{
return $this->belongsToMany('App\Models\Person','job_person','job_id','person_id');
}
}
这是 JobTitle 模型
class JobTitle extends Model
{
use Notifiable;
protected $table = "job_titles";
protected $primaryKey = 'job_title_id';
protected $fillable = [
'name',
];
protected $hidden = [
'token',
];
public function jobs()
{
return $this->hasMany('App\Models\Job','job_title_id');
}
}
现在我在控制器中的代码如下所示:
$job = Job::all()->load('title');
它工作正常,但是当我打电话给人们的工作时
$personJobs = Person::find(1)->jobs()->load('title')->get();
给出错误,任何想法如何做到这一点?