How sequelize works?

前端 未结 3 1852
时光取名叫无心
时光取名叫无心 2021-01-23 01:26

I\'m trying to understand how sequelize works on a simple example : User can have many posts and post can have only one user.

First question, I don\'t know if I have to

3条回答
  •  抹茶落季
    2021-01-23 02:13

    I am really just restrucuring your code.

    // Create One database config file

    var Sequelize=require('sequelize');
    
    var connection=new Sequelize('project','user','password',{
        dialect:'mysql',
        logging:false
    });
    
    connection.authenticate()
      .then(() => {    
        console.log("Connected to database");
      })
      .catch(err => {
        //console.error("Can't connect to database :(\n", err);
      });
    
    
    module.exports={
        database:connection,
    }
    

    //Your User Schema File

    var database = require('your_file_path/DatabaseConnection').database;
    
    var Sequelize = require('sequelize');
    
    var Users = database.define('users', {
    
        username: {
            allowNull: false,
            type: Sequelize.STRING,
            unique: true
        },
        password: {
            allowNull: false,
            type: Sequelize.STRING
        },
        email: {
            allowNull: false,
            type: Sequelize.STRING,
            unique: true
        }
    }, {
        underscored: true
    },hooks: {
        beforeCreate: (user, option) => {
            users.password = encrypto.encryptEntity(user.password);
            //for automatic encryption of password
        },
    
    }
    

    );

      Users.sync();
    
        //id, updated_at , and modified_at will be maintained by default
    
        module.exports = {
            Users
        }
    

    // your post file path

    var Posts = database.define('posts', {
    
        post_content: {
            allowNull: false,
            type: Sequelize.STRING,
            unique: true
        }
    }, {
        underscored: true
    });
    
    //importing User
    var Users = require('file_path')
    
    Users.hasMany(Posts, {
        foreignKey: 'user_id',
        sourceKey: 'user_id',
        onDelete: 'cascade',
        as:'Posts',
    });
    
    Posts.belongsTo(Users, {
        foreignKey: 'user_id',
        sourceKey: 'user_id',
        onDelete: 'cascade',
        as:'Users',
    }); 
    // two way binding.
    Posts.sync();
    

    BY maintaining Relation you can easily update data using setter and getter methods

    Posts.setUsers(user_object);
    

    // above code will automatically put the user_id found in user_object

    //for select query you can use:

    Users.findOne({
        where:{
            id:user_id
        },
        include: [{
            model: Posts,
            attributes: ['post_content'],
            as: "Posts"
        }//this will bring every posts user has created
    })
    

    I think above coding standard will make your code looks cleaner and will be more helpful for larger projects.

    Hope this helps.

提交回复
热议问题