0

Trying to figure what table I need to make this relationship to work...

I'd like the user to mark a post as favorite and save it so when he log back in, he can view all his favorite posts.

So I have User and Post models and their relationships of course.

User hasMany Post, Post belongTo User

Do I need to add Favorite model and add fav_id to both User and Post models ? Or maybe adding pivot table?

2
  • Is the User / Post relationship pertaining to which User created which Post? Or which post(s) are a User's favorite Posts? Commented Jun 10, 2014 at 4:57
  • I've updated the post and added my relationships Commented Jun 10, 2014 at 5:05

1 Answer 1

1

If a favorite is defined as a simple relationship between users and posts, you don't need a model for it. However, you do want a pivot table, call it something like favorites. It would contain id, post_id, user_id, created_at, updated_at.

Then in your user model:

public function favoritePosts()
{
  return $this->belongsToMany('Post', 'favorites');
}

And in the post model:

public function favoritedBy()
{
  return $this->belongsToMany('User', 'favorites');
}

So now, for any given user, you can do $user->favoritePosts to get an array of posts that user has "favorited".

And from a post object, you can do $post->favoritedBy, to get an array of users that have favorited that post.

I haven't tested this but that seems like that would work off the top of my head.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.