Laravel hasOneThrough-Laravel关系

时间:2019-12-23 10:36:06

标签: laravel eloquent

我真的需要以下帮助!我试图了解hasOneThrough的工作方式

用户表:

id | nobody_to(公司的ID)

公司表:

id | country_id

国家/地区表:

id

因此,我想通过用户模型通过公司了解用户的国家/地区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作为结果

1 个答案:

答案 0 :(得分:1)

如评论中所述,hasOneThrough并不是真正意义上的belongsTo关系,因为您只需将关系链接在一起即可获得所需的模型:

$user->company->country;

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

public function country()
{
    return $this->hasOneThrough(
        Countries::class, Companies::class, 'id', 'id', 'belongs_to', 'country_id'
    );
}