Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial




In my project i have elements stored in a database table. I want to allow the users of my website to add them to favorites.

I am not sure how to start with this one.

What is a good way to create favorites functionality?

2 Answers

Chema Castellanos
Chema Castellanos
3,984 Points

you can create a new table named favorites and add 2 fields, one for the username and other for the element id so you may have one user with many elements

Chema Castellanos answer should fix your issue, but instead of username I would use the user id against the element id. User numebrs where possible because they're a lot faster to index!

If you have a user with the id of 1 and an element of the id of 1, you would create a new row in your "favorites" table with values of 1 & 1. This would create the join between the element and the user.

The relationship is many-to-many because an element can be favorited by many users and a user can favorite many elements.

I think it's also good to add a table id for the 'favorite', giving you three columns in your joining table.