Mysql 在目标表具有一对一的情况下使用hasManyThrough

Mysql 在目标表具有一对一的情况下使用hasManyThrough,mysql,laravel,eloquent,Mysql,Laravel,Eloquent,如果我们采用hasManyThrough并将其更改为: countries id - integer name - string users id - integer country_id - integer website_id - integer name - string websites id - integer title - string 有用户作为中间关系,我可以使用国家模型上的hasManyThrough()来

如果我们采用
hasManyThrough
并将其更改为:

countries
    id - integer
    name - string

users
    id - integer
    country_id - integer
    website_id - integer
    name - string

websites
    id - integer
    title - string
用户
作为中间关系,我可以使用
国家
模型上的
hasManyThrough()
来获取
网站

我尝试了这个,结果是一个错误
namespace App;

use Illuminate\Database\Eloquent\Model;

class Country extends Model
{
    /**
     * Get all of the websites for the country.
     */
    public function websites()
    {
        return $this->hasManyThrough('App\Website', 'App\User');
    }
}
illumb\Database\QueryException:SQLSTATE[42S22]:未找到列:1054未知列


可能
用户
必须有许多
网站
才能使用此功能?

您可以根据@Samir的评论更改表结构以符合Laravel的期望,或者您可以自定义键以符合现有表结构

执行关系查询时,将使用典型的雄辩外键约定。如果要自定义关系的键,可以将它们作为第三个和第四个参数传递给hasManyThrough方法。第三个参数是中间模型上外键的名称。第四个参数是最终模型上外键的名称。第五个参数是本地键,而第六个参数是中间模型的本地键:

公共功能网站()
{
返回$this->hasManyThrough('App\Website','App\User','country\u id','id','Website\u id','Website\u id');
}

在表
网站
中缺少外键
用户id
。同样,在
用户
表中不需要有网站id。@Samir,但在我的示例中,
用户
只能有一个
网站
。我是否仍要将外键添加到
网站
?按照
的工作方式,您必须这样做。下面是从文档中得到的解释:
虽然帖子不包含国家/地区id列,但hasManyThrough关系通过$country->posts提供对国家/地区帖子的访问。要执行此查询,Elount将检查中间用户表上的country_id。在找到匹配的用户ID后,它们被用来查询posts表。
成功了!只需稍微修改一下
return$this->hasManyThrough('App\Website'、'App\User'、'country\u id'、'id'、'Website\u id'、'Website\u id')