Home  >  Article  >  Web Front-end  >  Nodejs version of orm library--sequelize

Nodejs version of orm library--sequelize

青灯夜游
青灯夜游forward
2020-09-09 10:12:232702browse

This article will take you through the nodejs database orm extension-sequelize. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

Nodejs version of orm library--sequelize

sequelize is the nodejs version of the ORM library. Those who have used laravelORM can get started quickly

[Video tutorial recommendation: node js tutorial]

Specific documentation

Simple code demo

const { Sequelize, DataTypes, Model, QueryTypes, Op } = require("sequelize");
const sequelize = new Sequelize("sqlite://sql.db", { logging: false });

class User extends Model {}
class Address extends Model {}

User.init(
  {
    // 在这里定义模型属性
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true,
    },
    name: {
      type: DataTypes.STRING,
      unique: true,
      // allowNull 默认为 true
      validate: {
        async isUnique(name) {
          const res = await User.findOne({where: {name}})
          if (res) throw new Error('用户名已存在')
        },
        // len: [1,2]
      }
    },
  },
  {
    // 这是其他模型参数
    sequelize, // 我们需要传递连接实例
    // modelName: "User", // 我们需要选择模型名称
    tableName:'users' // 表名,默认为模型名的复数单词
  }
);

Address.init(
  {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true,
    },
    name: {
      type: DataTypes.STRING,
      unique: true,
      // allowNull 默认为 true
    },
  },
  {
    sequelize,
    modelName: "Address",
  }
);

// 模型关系 多对多
User.belongsToMany(Address, { through: "userAddress", as:'addres' }); // through 代表中间表的名字,as是查询别名
Address.belongsToMany(User, { through: "userAddress" });

(async () => {
  try {
    // await sequelize.sync({ alter: true });  // 同步模型到数据库-创建表
    // const user = await User.findOne({ where: { name: {[Op.like]:'%小%'} } }); // 基本查询
    const [user] = await User.findOrCreate({where:{name:'小小'},include:'addres'}); // 顺带查询到关联模型的数据
    
    const [address] = await Address.findOrCreate({where:{name:'小小de地址'}});
    await user.addAddress(address); // 关联增加

    console.log(user.toJSON());
  } catch (e) {
    console.log(e);
  }
})();

For more programming-related knowledge, please visit:

Programming Teaching! !

The above is the detailed content of Nodejs version of orm library--sequelize. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete