Designing Database Models
Introduction: The Role of Models in Our Cooking App
Welcome back! In the last lesson, you learned how to set up a basic Express application and connect it to a SQLite database using Prisma. You also organized your code using a clear project structure. Now, we are ready to take the next step: designing the models that will represent our recipes, ingredients, and reviews in the database.
Models are blueprints for your data. They define what kind of information your app will store and how different pieces of data relate to each other. In our cooking app, models will help us keep track of recipes, the ingredients they use, and the reviews users leave.
By the end of this lesson, you will understand how to design these models and how to represent their relationships in code using Prisma.
From Real-World Concepts to ER Diagrams
Let’s start by thinking about the real-world things our app needs to keep track of:
- Recipes (like "Spaghetti Carbonara")
- Ingredients (like "eggs," "bacon," "spaghetti")
- Reviews (users rating and commenting on recipes)
To organize these, we use something called an Entity-Relationship (ER) diagram. This is a simple way to draw out how different types of data relate to each other.
Here’s a basic version for our app:
- A Recipe can have many Ingredients (and an ingredient can be used in many recipes).
- A Recipe can have many Reviews (but each review belongs to one recipe).
This diagram helps us plan how to structure our database tables and how they connect.
Understanding Primary Keys and Foreign Keys
Before we move on, let’s clarify two important concepts you’ll see in our models: primary keys and foreign keys.
What is a Primary Key?
A primary key is a unique identifier for each row in a database table. It makes sure that every record can be found and referenced easily. In Prisma, we define a primary key using the @id attribute.
For example, in our Prisma schema:
This means every recipe, ingredient, or review will have its own unique id.
