Chris
Chris

Reputation: 14198

laravel eloquent hasOneThrough foreign keys

I have the following structure:

**users**
id, company_id

**companies**
id, country_id

**countries**
id, name

Now I'd like to get the user with the company and country like this:

User::with('country')->get();

So I have added the relationship to my user model:

    public function country() {
        return $this->hasOneThrough(Country::class, Company::class);
    }

However, Eloquent is looking for a user_id column in the companies column instead of a company_id column in the users table:

select `countries`.*, `companies`.`user_id` as `laravel_through_key` 
from `countries` 
inner join `companies` on `companies`.`id` = `countries`.`company_id`

Upvotes: 0

Views: 578

Answers (1)

N69S
N69S

Reputation: 17205

As stated with details in the documentation

return $this->hasOneThrough(
            Country::class,
            Company::class,
            'id', // Foreign key on the Companies table...
            'id', // Foreign key on the Country table...
            'company_id', // Local key on the users table...
            'country_id' // Local key on the Companies table...
        );

One simpler solution would be to use the existing relation belongsTo

User::with('company.country')->get();

Upvotes: 1

Related Questions