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

青灯夜游
풀어 주다: 2020-09-09 10:12:23
앞으로
2687명이 탐색했습니다.

이 기사에서는 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으로 문의하세요.
    최신 이슈
    인기 튜토리얼
    더>
    최신 다운로드
    더>
    웹 효과
    웹사이트 소스 코드
    웹사이트 자료
    프론트엔드 템플릿
    회사 소개 부인 성명 Sitemap
    PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!