sequelize的应用

1、定义model

形式如下:

module.export=(sequelize)=> {

class ModelName extends Model {

}

ModelName.init({}, {});

}

module.exports = (sequelize) => {
  class User extends Model {
    /**
     * Create association between models
     * @param models the database models
     */
    static associate (models) {
      User._models = models
      User.hasMany(models.Opportunity, { foreignKey: 'ownerId', as: 'owners' })
      User.hasMany(models.DiscussionPost, { foreignKey: 'authorId', as: 'posts' })
    }

    /**
     * Get entity by id
     * @param id the entity id
     * @returns the User instance
     */
    static async findById (id) {
      const criteria = {
        where: {
          id
        }
      }
      const entity = await User.findOne(criteria)
      if (!entity) {
        throw new errors.NotFoundError(`id: ${id} "User" doesn't exists.`)
      }
      return { id: entity.id, name: entity.name, profilePic: entity.profilePicture }
    }

    /**
     * Get entity by name
     * @param name the entity name
     * @returns the User instance
     */
    static async findByName (name) {
      const criteria = {
        where: {
          name
        }
      }
      const entity = await User.findOne(criteria)
      if (!entity) {
        throw new errors.NotFoundError(`name: ${name} "User" doesn't exists.`)
      }
      return { id: entity.id, name: entity.name, profilePic: entity.profilePicture }
    }

    /**
     * Get entity by name
     * @param oktaUsername the entity oktaUsername
     * @returns the User instance
     */
    static async findByOktaName (oktaUsername) {
      const criteria = {
        where: {
          oktaUsername
        }
      }
      const entity = await User.findOne(criteria)
      if (!entity) {
        throw new errors.NotFoundError(`oktaUsername: ${oktaUsername} "User" doesn't exists.`)
      }
      return { id: entity.id, name: entity.name, profilePic: entity.profilePicture }
    }
  }

  User.init(
    {
      id: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        allowNull: false
      },
      name: {
        type: Sequelize.STRING(128),
        allowNull: false
      },
      profilePicture: {
        field: 'profile_picture',
        type: Sequelize.STRING(128),
        allowNull: false
      },
      oktaUsername: {
        field: 'okta_username',
        type: Sequelize.STRING(45),
        allowNull: false
      }
    },
    {
      schema: config.DB_SCHEMA_NAME,
      sequelize,
      timestamps: false,
      tableName: 'user'
    }
  )
  return User
}

2、管理多个Model

通过读取当前目录下的model文件,注册到模式管理器中

const fs = require('fs')
const path = require('path')

const Sequelize = require('sequelize')
const config = require('config')

const basename = path.basename(module.filename)
const db = {}
const sequelize = new Sequelize(config.DB_DATABASE, config.DB_USERNAME, config.DB_PASSWORD, {
  host: config.DB_HOST,
  dialect: config.DB_DIALECT,
  port: config.DB_PORT,
  logging: config.DB_LOGGING
})

fs
  .readdirSync(__dirname)
  .filter(file => (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js'))
  .forEach((file) => {
    const model = require(path.join(__dirname, file))(sequelize)
    db[model.name] = model
  })

Object.keys(db).forEach((modelName) => {
  if (db[modelName].associate) {
    db[modelName].associate(db)
  }
})

db.sequelize = sequelize
db.Sequelize = Sequelize

module.exports = db

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kgduu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值