如何使用模型中的数据作为条件查询关系?

问题描述 投票:0回答:2

我有一个Employee模型,它有一个Position模型。 Position模型有很多工资模型关系:

员工被分配到“职位”(例如软件开发人员)根据多年的经验,职位有很多工资

员工模型有一个“经验”字段,用于指示多年的经验

我想检索这个员工的薪水,考虑到他的职位和多年的经验

我正在尝试这样的事情:

(在我的职位模型中):

public function salaryForExperienceYears($years)
  {
    return $this->hasOne(Salary::class)
                ->where('experience', $years)
                ->first()
                ->salary
                ;
  }

(在我的控制器中,我想获取信息):

$employee->position->salaryForExperienceYears(1);

如果我硬编码“1”的年数,它的工作,逻辑上。但我想利用这位员工多年的经验,我不能这样做:

$employee->position->salaryForExperienceYears($employee->experience);

我该怎么办?

即使我可以使用这种结构来做到这一点,感觉还有更好的方法...因为“经验”已经是$ employee的财产......

同样的方式我有一个关系 - >位置,这是使用$ employee中可用的position_id字段“约束”结果,感觉应该有一种方式,体验字段也是“从上下文推断”这里(尽管它是不是在不同的表中的关系)

也许我应该使用其他类型的关系?

laravel relationship
2个回答
0
投票

试试这个:

$experience = $employee->experience;
$employee->position->salaryForExperienceYears($experience);

0
投票

使用左加入薪水体验年:

public function salaryForExperienceYears()
{
    return $this->hasOne(Salary::class)
                ->where('experience', new Expression('years'))
                ->lefftJoin('employees', 'id', 'employees_id')
                ->first()
                ->salary
                ;
}

要么

$position = $employee->position;
$selary = $position->salaryForExperienceYears($employee->experience);
© www.soinside.com 2019 - 2024. All rights reserved.