You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

0 Días
8 Hrs
20 Min
32 Seg

Resolviendo relaciones uno a muchos

19/27
Resources

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.

// We import the models from the SQLite libraryconst { models } = require('libs/sqlite-lib');
// Function to create a new categoryasync 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.

// Logic for creating new products and establishing relationshipsconst { 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', // Refers to the category};

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.

Contributions 17

Questions 17

Sort by:

Want to see more contributions, questions and answers from the community?

Creo que este no es un curso para principiantes.
Es muy sorprendente como navegamos por medio de las relaciones de la base de datos sin siquiera tener un modelo físico a mano para consultarlo y para que el desarrollo de los servicios y los modelos sea más explícito.
Por eso creo que un principiante podría tener algunas dificultades en este curso.
Sin embargo también creo que el profe explica de una manera muy natural como las entidades se relacionan y cómo llegamos a resolver cada escenario.

Muchachos, es importante agregar el atributo foreignKey al belongsTo que se agrega en la tabla de products. De lo contrario node agrega a los querys una columna que no existe. Por lo tanto todos los querys que intenten fallaran por que no consigue la columna.
.
Si agregas esto en tu clase de associate

  this.belongsTo(models.UsersRol, { as: 'rols'}) // to many users

Lo que sucedera es que node incluye en los script “rolsId” como si fuera una columna, que no fue asignada en el modelo y tampoco existe en la bbdd.
.
Como lo resuelves? Incluye esto.

  this.belongsTo(models.UsersRol, {foreignKey: 'id', as: 'rols'}) // to many users

Solo asi me permitio hacer los querys

Al igual que en la relación uno a uno, se hacen las respectivas asociaciones dentro de los servicios de categorías y productos.

product.service.js:

async create(data) {
    const newProduct = await models.Product.create(data);
    return newProduct;
  }

  async find() {
    const products = await models.Product.findAll({
      include: ['category'],
    });
    return products;
  }

category.service.js:

async create(data) {
    const newCategory = await models.Category.create(data);
    return newCategory;
  }

  async find() {
    const categories = await models.Category.findAll();
    return categories;
  }

  async findOne(id) {
    const category = await models.Category.findByPk(id, {
      include: ['products'],
    });
    return category;
  }

Cabe mencionar que se debe modificar el esquema de producto ya que un producto está asociado a un categoryId ya que el esquema de la validación (Joi) debe coincidir con la BD en la llave foránea.

product.schema.js:

const Joi = require('joi');

const id = Joi.number().integer();
const name = Joi.string().min(3).max(15);
const price = Joi.number().integer().min(10);
const description = Joi.string().min(10);
const image = Joi.string().uri();
const categoryId = Joi.number().integer();

const createProductSchema = Joi.object({
  name: name.required(),
  price: price.required(),
  description: description.required(),
  image: image.required(),
  categoryId: categoryId.required(),
});

const updateProductSchema = Joi.object({
  name: name,
  price: price,
  description: description,
  image: image,
  categoryId,
});

Otro aporte igual de importante. Si quieres capturar la exception de ForeignKey puedes agregar esto al middlelware de exceptions

const { ValidationError, ForeignKeyConstraintError } = require('sequelize')

Con esto puedes validar el tipo de excepcion colocando un if de la siguiente manera

if (err instanceof ValidationError && err.isBoom) { 
\\ respuesta
}else if(err instanceof ForeignKeyConstraintError && err.isBoom ){
// segunda respuesta
}
next(err) // Si no se cumple ninguna pasa al siguiente middlelware
Este curso hasta el momento me ha tomado bastante tiempo llegar a esta clase. He tenido un sin numero de inconvenientes al realizarlo, ya sea porque las versiones de la dependencias están muy actualizadas, o que algunas ya no se usan. pero sin duda me ha ayudado a combatir ese sindrome del impostor ya que he buscado alternativas y es gratificante ver que aunque no sea de la misma forma puedo hacer correr el proyecto. un curso realmente Avazando que me hace ver que todo el tiempo que dedique a la ruta de desarrollo web esta dando provecho. Nunca dejen de aprender compañeros!

bua me encanta lo util y realizta que es el curso

este curso es excelente

Me aparece este error al crear una categoría:
ValidationErrorItem {
message: ‘Category. id cannot be null’,
type: ‘notNull Violation’,
.
cuanlo lo solucione les comparto cual fue la solución.

  • Señalamos las relaciones

    • Los schemas de la DB y Joi deben coincidir en la foreign key
    • Podemos agregar la relación en los servicios
const { models }= require('./../libs/sequelize');

 async findOne(id) {
    const category = await models.Category.findByPk(id, {
      include: ['products']
    });
    return category;
  }

Me costó un poco entenderlo uwu

en la terminal corremos el comand: npm docs sequelize // ahí te abre la documentacion de como implementar las querys, no solo como el profe muestra en la clase, es importante curiosear y crear consultas que cotidianamente nos encontraríamos.

que bien explicado el curso, tiene toda mi atención, fabuloso!

Yo recuerdo que platzi tenía un apartado de apuntes dentro de la plataforma, pero ya no la veo, la quitaron

Quiten de name llave primaria!

Excelente curso.

El curso esta muy chido espero que más adelante también podamos ver cómo paginar y no solo una paginación simple sino como se vio ahora la necesidad, una paginación con muchos elementos traídos por asociación.

Excelente, me gusto esta clase. Nicolas explica muy bien

Buena clase