我确实需要以下帮助!我试图了解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
作为结果
正如评论中提到的,hasOneThrough
并不是真正意义上的belongsTo
关系,因为您只需将关系链接在一起就可以得到您想要的模型:
$user->company->country;
话虽如此,这应该是您想要的关系:
public function country()
{
return $this->hasOneThrough(
Countries::class, Companies::class, 'id', 'id', 'belongs_to', 'country_id'
);
}