尝试在English 中查看它而不是在PHP 中查看它,这样您就可以在正确的地方使用正确的功能。
所以你有 3 个表:company、jobs 和 employees
现在,在您深入了解 Laravel 中的模型之前,您需要了解这三个表之间的关系。
我假设公司和工作之间的关系是一对多的,这意味着一家公司可以有很多工作。
工作和员工之间的关系是一对一的,因为一份工作可以分配给一名员工。
现在根据您的项目,这些关系可能会有所不同,但第一步是建立三个表之间的关系。
现在,假设您确实具有我上面解释的相同关系,您的模型将具有以下“公共”功能:
//Company Model
//this function will returns all the jobs associated with the specific company_id
public function jobs()
{
return $this->hasMany('App\Job');
}
========
//Job Model
//this function will return the employee associated with the specific job_id
public function employee()
{
return $this->hasOne('App\Employee');
}
//now you can also have a function to fetch the company to which the job "belongs to", this is a reverse case which means, the jobs table has "company_id"
public function company()
{
return $this->belongsTo('App\Company');
}
您也可以在员工模型中执行相同的操作,因为每个员工都属于一个工作意味着有一个 job_id,因此您将使用 belongsTo 关系:
//Employee Model
//now you can also have a function to fetch the job to which the employee "belongs to", this is a reverse case which means, the employees table has "job_id"
public function job()
{
return $this->belongsTo('App\Job');
}
需要注意的一点是 hasOne 和 belongsTo 是相互对应的函数。
因此,如果 Job 模型使用 hasOne 作为 Employee,Employee 将使用 belongsTo 作为 Job,考虑到雇员表有“job_id”作为外键。重要的是您使用的是哪个模型,基于您可以使用这些函数获取另一个模型的详细信息。
更多详情当然可以参考official documentation。
我希望它能帮助你消除困惑