Laravel 5.2 - 通过多个表加入

时间:2018-05-15 11:01:59

标签: php laravel laravel-5 eloquent laravel-5.2

我有以下表格:

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');
}

但似乎无法正常工作

1 个答案:

答案 0 :(得分:1)

您可以使用数据透视表ManyToMany将您的关系定义为suggestions_for

用户模型

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

建议模型

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