Sequalize

Schema básico

import {db, DataTypes} from '@Application/database';

const ClassroomStudent = db.define('classroomstudent', {

  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true,
    allowNull: false,
  },
  auth0Id: {
    type: DataTypes.STRING,
    unique: true
  },
  hasTerminated: {
    type: DataTypes.BOOLEAN,
    defaultValue: false
  },
  doubtTime: DataTypes.TIME
});

Crud básico

    create(data) {
        return Model.create(data);
    },
    get(conditions) {
        return Model.findAll(conditions ? {where:conditions} : {});
    },
    getById(id) {
        return Model.findOne({ where: { id } });
    },
    updateById(id, data) {
        return Model.update(data, { where: { id } });
    },
    update(conditions, data) {
        return Model.update(data, { where: conditions });
    },
    deleteById(id) {
        return Model.destroy({ where: { id } });
    },
    findOrCreate(condition, newObj){
        return Model.findOrCreate({where:condition, defaults: newObj});
    }

Consultas Many to Many

Schema De Classroom

const ClassRoom = db.define('classroom', {
	...
});

ClassRoom.associate = ({ student }) => {
	ClassRoom.belongsToMany(student, { through: 'classroomsusers', onDelete: 'cascade' });
};

Schema de Student

import {db} from '@Application/database';
const {DataTypes} = require('sequelize');

const Student = db.define('student', {
   ...
});

Student.associate = ({ classroom }) => {
    Student.belongsToMany(classroom, { through: 'classroomsusers', onDelete: 'cascade' });
};

export default Student;

Definir la tabla intermedia con atributos de relación

Los atributos de relación que hemos añadido en este caso son hasTerminated y isInClassroom.

En la tabla que usamos para establecer las relaciones tendremos que definir expresamente el campo id.

import {db, DataTypes} from '@Application/database'

const ClassroomUser = db.define('classroomuser', {
    id: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true,
        allowNull: false,
    },
    hasTerminated: DataTypes.BOOLEAN,
    isInClassroom: DataTypes.BOOLEAN
});

ClassroomUser.associate = ({classroom, student}) => {
    ClassroomUser.belongsTo(classroom);
    ClassroomUser.belongsTo(student);
};

export default ClassroomUser;

Configuración de las relaciones

export const setAssociations = (db) => {
	Object.keys(db.models).forEach((modelName) => {
		if ('associate' in db.models[modelName]) {
			db.models[modelName].associate(db.models);
		}
	});
};

Operaciones con relaciones Many to Many

Consulta de una clase con sus respectivos alumnos

import Schema from './schema';
import Student from '../../student/model/schema';

const Model = {
    getClassroomWithStudents(conditions){
        return Schema.findOne({where:conditions,include: Student});
    }
};

export default Model;

Crear un estudiante vinculado a una clase

const [classroom] = await ClassroomModel.get({teacherId:msg.teacherId, cod: msg.cod});
if (classroom) {
  const student = await Model.create({auth0Id: msg.auth0Id, picture: msg.picture, name: msg.name});
  // creamos la relación en la tabla de relaciones
  ClassroomStudentModel.create({studentId: student.id, classroomId: classroom.id}); 
  return classroom;
}
← Actualizar un proyecto de NodeJS
Cómo usar Swagger para visualizar las peticiones REST en NodeJS →

Aviso Legal | Política de privacidad