Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

PHP

Favorites

Hello,

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.