Laravel hasOneThrough-Laravel关系

问题描述 投票:0回答:1

我确实需要以下帮助!我试图了解hasOneThrough的工作原理

用户表:

id | Emirates_to(公司的ID)

公司表:

id | country_id

国家表:

id

所以我想通过User模型通过Company知道用户的国家/地区ID,我正在尝试以下操作:

public function country() {
        return $this->hasOneThrough(
            'App\Countries',
            'App\Companies',
            'country_id', // the name of the foreign key on the intermediate model...
            'id', // is the name of the foreign key on the final model...
            'belongs_to', // is the local key...
            'id' // is the local key of the intermediate model...
        );
    }

也尝试过

public function country() {
        return $this->hasOneThrough(
            'App\Countries',
            'App\Companies',
            'country_id', // the name of the foreign key on the intermediate model...
            'belongs_to', // is the name of the foreign key on the final model...
            'id', // is the local key...
            'id' // is the local key of the intermediate model...
        );
    }

但是总是得到NULL作为结果

laravel eloquent
1个回答
0
投票

正如评论中提到的,hasOneThrough并不是真正意义上的belongsTo关系,因为您只需将关系链接在一起就可以得到您想要的模型:

$user->company->country;

话虽如此,这应该是您想要的关系:

public function country()
{
    return $this->hasOneThrough(
        Countries::class, Companies::class, 'id', 'id', 'belongs_to', 'country_id'
    );
}
© www.soinside.com 2019 - 2024. All rights reserved.