简体   繁体   中英

Many-To-Many Recipe Database SQL

I have a many-to-many relationship for a recipe database project I'm working on to learn php/mysql.

Recipes Table

recipe_id

Ingredient List Table

recipe_id
ingredient_id
amount

Ingredients Table

ingredient_id
ingredient_name

The user is the one entering the ingredient names into the html form. They are not pre-entered into the database by me.

My question is, how do I query the database so that:
1.) the name of the ingredient is entered into the ingredients table (only if it does not already exist)
2.) also insert it into the correct ingredient list for the correct recipe?

I must be missing some aspect here that will make this concept 'click' for me. I think that, at least, my tables are correct.

This is best solved by running multiple queries inside a transaction.

  1. Check if ingredient exists (or add a unique index on ingredient name and catch error on insert if it's a duplicate)
  2. Insert ingredient
  3. Insert into ingredient list
  4. Commit transaction

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM