首页 > 解决方案 > laravel 雄辩 hasOneThrough 外键

问题描述

我有以下结构:

**users**
id, company_id

**companies**
id, country_id

**countries**
id, name

现在我想让用户像这样使用公司和国家:

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

所以我已将关系添加到我的用户模型中:

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

但是,Eloquent 会在 Companies 列中查找 user_id 列,而不是在 users 表中查找 company_id 列:

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

标签: laraveleloquentforeign-keysrelationship

解决方案


如文档中的详细信息所述

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...
        );

一种更简单的解决方案是使用现有的关系belongsTo

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

推荐阅读