# Sequalize

## Introduction



![](https://1374779285-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFW3x2aqEO8GF2kr3VU%2Fuploads%2F62cSzkJwBk3u4mZzWd2z%2Fscreenshot-www.udemy.com-2022.11.07-22_39_00.png?alt=media\&token=0071c867-5263-4ede-857a-80aa9b41ab8f)

* 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

![](https://1374779285-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFW3x2aqEO8GF2kr3VU%2Fuploads%2FO8kOLAZ2FQZ3kunN9IWT%2Fscreenshot-www.udemy.com-2022.11.08-01_18_45.png?alt=media\&token=c85e650c-17a3-45eb-bda8-d1feaf3d6719)

* 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

```javascript
// 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

```javascript
const Sequelize = require('sequelize');

const sequelize = require('../util/database');

const Product = sequelize.define('product', {
  id: {
    type: Sequelize.INTEGER,
    autoIncrement: true,
    allowNull: false,
    primaryKey: true
  },
  title: Sequelize.STRING,
  price: {
    type: Sequelize.DOUBLE,
    allowNull: false
  },
  imageUrl: {
    type: Sequelize.STRING,
    allowNull: false
  },
  description: {
    type: Sequelize.STRING,
    allowNull: false
  }
});

module.exports = Product;
```

## Create table

```javascript
const sequelize = require('./util/database');

// Create the table based on the modal definition if the mapped table doesn't exist
sequelize.sync();
```

## CRUD Operation

```javascript
const Product = require('../models/product');

// Fetch all products
Product.findAll(
    // {
        // where:{
            // ...
        }
    // }
).then(products =>{
    // ...
}).catch(err=>{
    // ...
});

// Find by id
Product.findById(prodId).then(product =>{
    // ...
}).catch(err=>{
    // ...
});


// Create
Product.create({
    title: title,
    price: price,
    // ...
})


// Update
Product.findById(prodId)
.then(product => {
      product.title = updatedTitle;
      product.price = updatedPrice;
      product.description = updatedDesc;
      product.imageUrl = updatedImageUrl;
      return product.save();
});

// Delete
Product.findById(prodId).then(product => product.destroy());
```

## Associations

* Create the relationship between tables by creating foreign key automatically

```javascript
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();
```
