Reputation: 83
I am trying to implement a feature and I don't think it's available by relationships.
A User may have many Companies and Company may have many Users. They are connected via company_employees pivot table.
pivot table looks like this:
company_id, user_id, position_id
I want to have an option to fetch company employees with their assosiated position.
Let's say there are companies:
and user
There are also 2 positions:
John Doe is an employee in both of these companies with different position.
company_id | user_id | position_id
1 1 1
2 1 2
How can i make something like
$company = Company::first();
$company->employees()->with('position')->get();
return only position associated with first user that belongs to first company as HasOne relationship?
Upvotes: 3
Views: 115
Reputation: 1502
I think you can only achieve it by using a custom with
function.
Untested code:
$company = Company::first();
$company->employees()->with([
'position' => function ($query) use ($company) {
$query->where('company_id', $company->id);
}
])->get();
Check out the documentation.
Upvotes: 0
Reputation: 80
Company.php
public function user() {
return $this->belongsToMany('App\User', 'company_employees ', 'company_id',
'user_id');
}
User.php
public function position() {
return $this->hasMany('App\Position');
}
$company = Company::with('user.position')->get();
Upvotes: 1