It is an object-relational mapping library that it does all sql command behind the scene to map the database table to the javascript object without writing sql command, but do database operation with help of helper function
In general, It is needed to create a modal that maps to database table , and create the instance based on that, so that new record will be added into table
It is also allowed to execute function to perform CRUD operation, but also can check the association between the table
Connect to mysql
// The connection is still established by using mysql2 library behind the scene
const Sequelize = require('sequelize');
const sequelize = new Sequelize('node-complete', 'root', 'nodecomplete', {
dialect: 'mysql',
host: 'localhost'
});
module.exports = sequelize;
Modal Definition
Define the modal where the type should be matched with table schema
Create the relationship between tables by creating foreign key automatically
const Product = require('./models/product');
const User = require('./models/user');
const Cart = require('./models/cart');
const CartItem = require('./models/cart-item');
const Order = require('./models/order');
const OrderItem = require('./models/order-item');
// One to one relation
User.hasOne(Cart);
// Create user id automatically to the cart table as a foreign key
Cart.belongsTo(User);
const user = User.create({...});
// Create new record with user id as a foreign key
user.createCart({..});
user.getCart();
// One to many relation
User.hasMany(Product);
// When user is deleted, the related products are also be deleted due to cascade policy
Product.belongsTo(User, { constraints: true, onDelete: 'CASCADE' });
const user = User.create({...});
user.getProducts();
user.createProduct();
// Many to many relationship
// Cart item will be created , containing the key of cartid and product id
Cart.belongsToMany(Product, { through: CartItem });
Product.belongsToMany(Cart, { through: CartItem });
cart.getProducts();
cart.addProducts();
product.getCarts();