platypusmaximus
platypusmaximus

Reputation: 83

Laravel: Loading nested relationship only for related model

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:

  1. "Foo Company"
  2. "Bar Company"

and user

  1. "John Doe"

There are also 2 positions:

  1. "Frontend Developer"
  2. "Backend Developer"

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

Answers (2)

Cloud Soh Jun Fu
Cloud Soh Jun Fu

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

Manisha
Manisha

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

Related Questions