Q: How to query relationship using data from model as a condition? I have an Employee model, which hasOne Position model.
The Position model hasMany salaries model relationhip:
An employee is assigned to a "position" (eg Software developer)
A position has many salaries, depending on years of experience
The employee model has an "experience" field to indicate the years of experience
I want to retrieve the salary for this Employee, taking into account its position and years of experience
I'm trying something like:
(in my Position model):
public function salaryForExperienceYears($years)
  {
    return $this->hasOne(Salary::class)
                ->where('experience', $years)
                ->first()
                ->salary
                ;
  }

(in my controller, where I want to get the info):
$employee->position->salaryForExperienceYears(1);

if I hardcode "1" for the num of years, it works, logically.
but I want to use this employee's years of experience, and I can't do that:
$employee->position->salaryForExperienceYears($employee->experience);

How should I do it?
Even if I can get a way of doing this using this structure, it feels like there's a better way of doing it... because "experience" is already a property in $employee...
the same way I have a relationship for ->position which is "constraining" the results using the position_id field available in $employee, it feels like there should be a way where the experience field is also "inferred from context" here (although it's not a relationship in a different table)
Maybe I should be using some other type of relationship?

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

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


A: Try this:
$experience = $employee->experience;
$employee->position->salaryForExperienceYears($experience);

