>  기사  >  웹 프론트엔드  >  Orm 라이브러리의 Nodejs 버전--sequelize

Orm 라이브러리의 Nodejs 버전--sequelize

青灯夜游
青灯夜游앞으로
2020-09-09 10:12:232646검색

이 기사에서는 nodejs 데이터베이스 또는 Extension-sequelize를 안내합니다. 도움이 필요한 친구들이 모두 참고할 수 있기를 바랍니다.

Orm 라이브러리의 Nodejs 버전--sequelize

sequelize是nodejs版的orm库,用过laravelORM빠르게 시작할 수 있습니다

간단한 코드 데모

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);
  }
})();

업데이트됨 더 많은 프로그래밍 관련 지식을 보려면

프로그래밍 교육

을 방문하세요! !

    위 내용은 Orm 라이브러리의 Nodejs 버전--sequelize의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

    성명:
    이 기사는 segmentfault.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제