Laravel 5.2 - 通过多个表加入

Laravel 5.2 - Join through multiple tables

我有以下表格:

User
    id

Suggestions_For
    id
    user_id
    suggested_account

Suggestions
    id

(User.id = Suggestions_For.user_id)
(Suggestions_For.suggested_account = Suggestions.id)

如果我想像这样为用户获取所有建议: $用户->建议()->计数()

我该怎么做?有没有办法在我的模型中定义一个关系,该关系通过多个数据透视表将用户加入建议?

我试过:

public function suggestions()
{
    return $this->hasManyThrough('App\Suggestions', 'App\Suggestions_For', 'suggested_account', 'id');
}

但似乎不起作用

您可以使用枢轴 table suggestions_for as

将您的关系定义为 ManyToMany

用户模型

public function suggestions()
{
    return $this->belongsToMany(Suggestions::class, 'suggestions_for', 'user_id')
}

建议型号

public function users()
{
    return $this->belongsToMany(User::class, 'suggestions_for', 'suggested_account ')
}