Sequelize常用操作

 Sequelize是一個基於Node.js的一款ORM框架,目前支持 Postgres, MySQL, MariaDB, SQLite 以及 Microsoft SQL Server數據庫。支持事務、 關聯關係、 預讀、延遲加載、讀取複製等功能。

Sequelize官網文檔有點過於簡潔了,數據庫-模型之間的一些複雜但是非常實用的操作並沒有收錄,所以這篇文章是Sequelize對數據庫一些常見操作的實踐記錄。基於我踩的一對坑撰寫,可能有點像流水賬,開始之前需要你對Sequelize的基本概念有所瞭解。

創建User表:

User.init(
  {
    id: {
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV1,
      primaryKey: true,
    },
    username: {
      type: DataTypes.STRING,
    },
    avatar: {
      type: DataTypes.STRING,
      // 試了一下校驗功能沒起作用,希望瞭解這塊的指點迷津
      // validate: {
      //   isUrl: {
      //     args: {
      //       require_host: false,
      //     },
      //     msg: '必須URL格式',
      //   },
      // },
    },
    phone: {
      type: DataTypes.STRING,
    },
    email: {
      type: DataTypes.STRING,
      validate: {
        isEmail: true,
      },
    },
    password: {
      type: DataTypes.STRING,
    },
    disabled: {
      type: DataTypes.BOOLEAN,
      defaultValue: 0,
    },
  },
  {
    sequelize,
    timestamps: true,
    // updatedAt: 'updated_at', // 設置更新時間字段
    // createdAt: 'created_at', // 設置創建時間字段
    defaultScope: {
      // 查詢時默認不返回密碼
      attributes: { exclude: ['password'] },
    },

  },
)

創建角色表:

Role.init(
  {
    id: {
      type: DataTypes.STRING,
      primaryKey: true,
    },
    name: {
      type: DataTypes.STRING,
    },
  },
  {
    sequelize,
    timestamps: true,
  },
)

創建用戶-角色中間表(多對多):

UserRole.init({
  status: DataTypes.INTEGER,
  UserId: {
    type: DataTypes.INTEGER,
    references: {
      model: User,
      key: 'id',
    },
  },
  RoleId: {
    type: DataTypes.INTEGER,
    references: {
      model: Role,
      key: 'id',
    },
  },
}, {
  sequelize,
  timestamps: true,
})

創建多對多關係:

User.belongsToMany(Role, {through: UserRole})
Role.belongsToMany(User, {through: UserRole})

創建反饋表:

Feedback.init(
  {
    content: {
      type: DataTypes.STRING,
    },
    attachments: {
      type: DataTypes.TEXT,
    },
    state: {
      type: DataTypes.INTEGER,
      defaultValue: 0,
    },
  },
  {
    sequelize,
    timestamps: true,
  },
)

創建反饋與用戶的一對多關係

// 反饋創建人
Feedback.belongsTo(User, { foreignKey: 'CreatorId', as: 'Creator' })
// 反饋處理人
Feedback.belongsTo(User, { foreignKey: 'HandlerId', as: 'Handler' })

獲取我的反饋列表:

// 反饋列表包含處理人和創建人的id、username
await Feedback.findAll({
  include: [
    { model: User, as: 'Creator', attributes: ['id', 'username'] },
    { model: User, as: 'Handler', attributes: ['id', 'username'] },
  ],
})

查詢產品列表:

await Product.findAll({
  attributes: { exclude }, // 去掉產品表中的某些字段
  include: [{
    model: Category,
    through: {
      attributes: [], // 不需要聯結表中的內容
    },
  }],
})

添加產品:

const newProduct = Product.build({ // build非異步方法
  name: product.name,
  price: product.price,
  cover: product.cover,
  detail: product.detail,
})
if (product?.categories?.length) {
  // 獲取分類實例列表
  const categoryEntityList = await Category.findAll({
    where: {
      id: product.categories,
    },
  })
  // 設置產品類別
  categoryEntityList.length && newProduct.setCategories(categoryEntityList)
}
await newProduct.save() // save是異步方法,需要await

刪除產品:

await Product.destroy({
  where: { id },
})

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章