How to create a new category in SQLite?
We start with the logic of creating categories using SQLite. The key is to import the correct models from our internal library and use asynchronous methods to handle database operations.
const { models } = require('libs/sqlite-lib');
async function createCategory(data) { const newCategory = await models.Category.create(data); return newCategory;}
This simple code snippet allows the creation of a category and ensures that all validations in the schema are met, requiring a name and an image to complete successfully.
How to create a product and manage one-to-many relationships?
To manage product creation and establish one-to-many relationships, we first integrate our product model.
const { models } = require('libs/sqlite-lib');
async function createProduct(data) { const newProduct = await models.Product.create(data); return newProduct;}
What settings are required in the schema?
The product schema must include a reference to the category ID to establish the relationship. This is where we specify that a product must belong to a specific category.
const productSchema = { name: 'string', price: 'integer', description: 'string', categoryId: 'integer', };
How to query products and categories with associations?
A vital part is to query items with their correct associations. To do this, we make use of the built-in search methods:
How to search for products with their categories?
async function getProducts() { const products = await models.Product.findAll({ include: [{ model: models.Category, as: 'category' }]} ); return products;}
How to find a category and its products?
This method shows how to get a particular category and all the products associated with it.
async function getCategoryWithProducts(categoryId) { const category = await models.Category.findByPk(categoryId, { include: [{ model: models.Product, as: 'products' }]} ); return category;}
What is the process for querying and getting a detailed summary?
- General product query: Returns products with their categories thanks to the inclusion of associations.
- General category query: Returns only categories, without additional product details, for light operations.
- Specific category detail: When the breakdown of a product is needed, a deeper search including all its products is performed using
includes: products
.
With these steps, it is possible to manage multiple one-to-many relationships, allowing you to create a more efficient and consistent data flow within a developing application. Stay tuned to learn how to handle more complex many-to-many relationships.
Want to see more contributions, questions and answers from the community?