One to Many to One relationship How to do One to Many to One relationship in Laravel. I have three tables company, employee and motorcycle. One company has many employee. One employee has one motorcycle.
How can I do that Eloquent relationship in controller ?
Did you try hasManyThrough relationship. See docs .
In your Company model:
public function motorcycles()
{
return $this->hasManyThrough(Motorcycle::class, Employee::class);
}
then you can retrive all the motorcycles within a company as:
$company->motorcycles;
//or eager load like this.
$companies = Company::with('motorcycles')->get();
Set your one to many (company -> employees) and one to one (employee -> moto) relation in the related models.
You can retrieve them with nested relations
https://laravel.com/docs/5.6/eloquent-relationships#eager-loading
$companies = Company::with('employees.motorcycle')->get();
Has many through should work too, but will not retrieve the data of employees.
Please sign in or create an account to participate in this conversation.