1
votes

I have 3 tables users, companies and pivot table with user_id, company_id. I can't get users, which belongs to my company inside User model. Tried like

belongsToMany('App\User','companies_users','company_id','user_id' );

but I get relation with wrong users.

1
How are you using the relationship? What's your query?Jonas Staudenmeir
@JonasStaudenmeir User::where('id',$user->id)->with('myCompany')->get() ,it is for director who has only one company.Vit
Is myCompany the relationship you posted?Jonas Staudenmeir

1 Answers

0
votes

Since you are having a belongsToMany relationship between the User and Company, the User belongs to more than one Company. To get users of the companies of a particular User will not be straight forward. If you are sure that is exactly what you want, then do this:

//inside the User model
public function companies()
    {
        return $this->belongsToMany('Company');
    }

//inside the User model
public function companiesusers()
    {
        $users= new Illuminate\Database\Eloquent\Collection;

        foreach($this->companies as $company)
        {
            $users = $users->merge($company->users->get());
        }

        return $users->unique();
    }

//inside the Company model
    public function users()
        {
            return $this->belongsToMany('User');
        }

Then you can get a user's companiesusers like so:

User::first()->companiesusers();