Today I want to talk about database associations. There are three types of association. One to One, One to Many and Many to Many. Let's look at how they are implemented with sequelize.





Before do the sync.. we need to add the association  (relation setup)

in App.js
==========

/*one product owned by one perticular user
so it is one to one relation*/

Product.belongsTo(User,{constraints:true,onDelete:"CASCADE"});

/*one user can have many products
so it is one to many relation*/

User.hasMany(Product);


Then we can add the sync

sequalize
  .sync({ force: true })   we do force for delete the table and recreates it.
  .then((res) => {        (After the changes are applied-> remove the force )
 
    return User.findByPk(1); we create a dummy user for now.
later-> Login Page :)
   
  })
  .then((user) => {
    if (!user) {
      return User.create({
        name: "Yasas",
        email: "yasassandeepa007@gmail.com",
      });
    }
    return user;
  })
  .then((usr) => {
    console.log(usr);
    app.listen(3000);
    console.log("Server running at http://127.0.0.1:3000/");
  })
  .catch((err) => {
    console.log(err);
  });


Register a New Middleware to store the user in a request. 

So, it can be accessed by anywhere.
note - > this middleware should be above all the requests..

app.use((req, res, next) => {
   
  This middleware only execute after successfully created the server
  (after the Sequelize function)
  always runs when new request happens
 
 
  User.findByPk(1)  <- take the dummy user
    .then((user) => {
      req.user = user;      adding the user into the request
     
      next();           IMP next for calling the next middleware
(to execute below routes)
    })
    .catch((err) => {
     
      console.log(err);
    });
});


Magic of Sequelize

Sequelize-> Automatically creates a method -> create<ModelName> to relavant Relation
Call the method according to the relation.
ex:- products has many carts => product.getCarts
<- 's' should be there (Do not worry…! you have IntelliSense :D )
(Wait for next Episode to More Explanations)


exports.postAddProduct = (req, res, next) => {
 
  const title = req.body.title;
  const imgUrl = req.body.imgUrl;
  const price = req.body.price;
  const description = req.body.description;

  req.user
    .createProduct({   <-Magic
      title: title,
      imgUrl: imgUrl,
      price: price,
      description: description,
    })
    .then((result) => {
      console.log(result);
      console.log("Successfully added..!!");
      res.redirect("/");
    })
    .catch((err) => {
      console.log(err);
    });
};


Get products according to the user  -> req.user.get<ModelName>()

req.user
    .getProducts()  <-Magic
    .then((products) => {
      res.render("admin/products", {
        prods: products,
        pageTitle: "Admin Product List",
        hasProducts: products.length > 0,
        active: "adminProducts",
      });
    })
    .catch((err) => {
      console.log(err);
    });