Home > Back-end >  Eloquent Relationships: user hasmany posts has many comments
Eloquent Relationships: user hasmany posts has many comments

Time:05-21

I'm using laravel and i am trying to create my database with Users, this user will have many comments and many posts, the catch is that the post also need to have many comments that all will belong to a post. And that the comments from the user will belong to a post.

Maybe im thinking about it in the wrong way, but cant figure it out.

Help is apriciated

Image representing what i want

CodePudding user response:

A comment can belongTo both a Post and a Comment. So, a solution could look something like this:

Relationships

User

  • hasMany Post
  • hasMany Comment

Post

  • belongsTo User
  • hasMany Comment

Comment

  • belongTo User
  • belongsTo Post

Models

User
id
Post
id
user_id
Comment
id
user_id
post_id
  • Related