Search code examples
phplaraveleloquentlaravel-9eloquent-relationship

How to realise a belongsToThrough relationship in Laravel 9 / 10?


There are three models: Employer, Instance, Worker.

The important fillables of the models are:

  • Employer
    • company_name
  • Instance
    • worker_id
    • employer_id
  • Worker
    • name

In consequence I have:

class Employer {
    public function instances()
    {
        return $this->hasMany(Instance::class);
    }
}
class Instance {
    public function worker()
    {
        return $this->belongsTo(Worker::class);
    }

    public function employer()
    {
        return $this->belongsTo(Employer::class);
    }
}

What I want to have is something like

class Worker {
    public function employer()
    {
        return $this->belongsToThrough(Instance::class, Employer::class);
    }
}

but this function does not exist. The SQL would be:

select e.company
from employers e
join instances i on i.employer_id = e.id
join workers w on w.id = i.worker_id
where w.id = ?

Finally I want to be able to use:

$workers_company = Worker::find(1)->employer->company_name;

Solution

  • You need a hasOneThrough relationship, with the final table/class as the first parameter, and the intermediate table/class as the second parameter (has one Employer through an Instance).

    class Worker {
        public function employer()
        {
            return $this->hasOneThrough(Employer::class, Instance::class);
        }
    }