【问题标题】:laravel eloquent hasOneThrough foreign keyslaravel 雄辩 hasOneThrough 外键
【发布时间】:2021-10-02 09:41:59
【问题描述】:

我有以下结构:

**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 列,而不是 users 表中的 company_id 列:

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

【问题讨论】:

    标签: laravel eloquent foreign-keys relationship


    【解决方案1】:

    如文档中的详细说明所述

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

    【讨论】:

      猜你喜欢
      • 2020-10-23
      • 2020-06-03
      • 1970-01-01
      • 2020-08-20
      • 2017-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多