Php Laravel 5.2-通过多个表连接
我有以下表格:Php Laravel 5.2-通过多个表连接,php,laravel,laravel-5,eloquent,laravel-5.2,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) 如果我想像这样获得用户的所有建议: $user->suggestions()->count() 我怎么做?有没有办法在我的
User
id
Suggestions_For
id
user_id
suggested_account
Suggestions
id
(User.id = Suggestions_For.user_id)
(Suggestions_For.suggested_account = Suggestions.id)
如果我想像这样获得用户的所有建议:
$user->suggestions()->count()
我怎么做?有没有办法在我的模型中定义一种关系,它通过多个透视表将用户加入到建议中
我试过:
public function suggestions()
{
return $this->hasManyThrough('App\Suggestions', 'App\Suggestions_For', 'suggested_account', 'id');
}
但似乎不起作用您可以将您的关系定义为使用透视表
建议作为
用户模型
public function suggestions()
{
return $this->belongsToMany(Suggestions::class, 'suggestions_for', 'user_id')
}
建议模型
public function users()
{
return $this->belongsToMany(User::class, 'suggestions_for', 'suggested_account ')
}
这似乎是一种简单的manytomy
关系。还是我错了?我已经有一段时间没有接触过laravel了。@ariel先试试,在用户对象上你可以得到相关的建议,比如$user->suggestions()->get()
同样地,在建议对象上你可以得到相关的用户$suggestion->users()->get()
。我已经发布了一个使用pivot Table的多对多示例,错误是:在null上调用成员函数get(),$user->suggestions()返回null@ariel对不起,我忘记在$this->belongtomany
之前添加return
,太棒了,谢谢!!正确的代码是:public function suggestions(){return$this->belongsomany(suggestions::class,'suggestions\u for','user\u id','suggestive\u account')}