Laravel关系混乱

时间:2019-02-14 10:24:34

标签: php database laravel reference

这些天我正在学习Laravel,并且想要创建一些表,模型和东西。

我有公司,工作和员工。如果我理解正确,那么模型文件中的公共函数就是字段:

 public function jobs()
  {
    return $this->hasMany('App\Job');
  }

这是否意味着我可以像这样为currentJob创建另一个函数:

 public function currentJob()
  {
    return $this->hasOne('App\Job');
  }

此外,我是否需要为每个关系添加belongsTo?例如,在用户模型中?

2 个答案:

答案 0 :(得分:2)

尝试在English中查看,而不是在PHP中查看,这样您就可以在正确的位置使用正确的功能。

因此,您有3个表:公司,职位和员工

现在,在Laravel中深入研究Model之前,您需要了解这三个表之间的关系。

我认为公司与工作之间的关系是一对多的,这意味着一家公司可以有很多工作。

工作与雇员之间的关系是一对一的,因为可以将一项工作分配给一名雇员。

现在根据您的项目,这些关系可能有所不同,但是第一步是在三个表之间建立关系。

现在,假设您确实具有如上所述的关系,那么您的模型将具有以下“公共”功能:

//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表具有“ job_id”作为外键,Employee将对Job使用belongsTo。使用哪个模型就很重要,您可以基于这些模型使用这些函数来获取另一个模型的详细信息。

当然,有关更多详细信息,请参见official documentation我希望它可以消除您的困惑

答案 1 :(得分:1)

对于基本模型关系:

// Job Model

public function employee(){
    return $this->belongsTo('App\Employee');

}

// Employee Model
public function jobs(){
   return $this->hasMany('App\Job');
}

如果要获得当前工作,可以添加appended property

// Employee Model

protected $appends = ['current_job'];

//Then create function for  the same : 

public function getCurrentJob()
{
  return $this->jobs()->latest()->first();
}
相关问题