Does this one help? http://laravel.com/docs/4.2/eloquent#has-many-through
Jan 5, 2015
15
Level 1
Discussion Comment User relationship
Hi i have three tables
Users
- id
- name
- email
Discussion
- id
- title
Comment
- id
- comment
and i have a pivot table
comment_discussion
- id
- discussion_id
- comment_id
- user_id
now i am fetching all related comments from the discussion like this:
$comments = $discussion->comments;
my question is as my pivot table has a connection to user_id also how will i get user details ?
i have added this to user model:
public function comments()
{
return $this->belongsToMany('Comment', 'comment_discussion')->withPivot('user_id');;
}
Any help will be appreciated.
Level 56
So your schema is over-complicated.
You just need three tables, Discussions, Comments, Users.
- Discussions hasMany Comments / Comments belongsTo a Discussion (discussion_id on comments table)
- User hasMany Comments / Comments belongsTo a User (user_id on comments table)
Then :
$discussion = Discussion::findOrFail($discussion_id);
echo $discussion->title;
foreach($discussion->comments as $comment)
{
echo $comment->comment;
echo $comment->user->name;
}
1 like
Please or to participate in this conversation.