laravel eloquent 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 正在寻找公司列中的 user_id 列,而不是用户表中的 company_id 列:

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

解决方法

如文档中所述

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