nodejs數據庫orm擴展-sequelize

sequelize是nodejs版的orm庫,用過 laravelORM的能很快能上手

具體文檔

簡單代碼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);
  }
})();
相關文章
相關標籤/搜索