富贵资源网 Design By www.hznty.com

sequelize.define

使用该方法可以定义model,例子如下:

const Sequelize = require('sequelize');

var sequelize = new Sequelize(config.database, config.username, config.password, {
 host: config.host,
 dialect: 'mysql',
 pool: {
  max: 5,
  min: 0,
  idle: 30000
 }
});

var Website = sequelize.define('website', {
 id: {
  type: Sequelize.BIGINT,
  primaryKey: true,
  autoIncrement: true
 },
 url: Sequelize.STRING(255),
 title: Sequelize.STRING(255),
 status: Sequelize.INTEGER,
 delete_mark: Sequelize.BOOLEAN
}, {
 timestamps: false
});

该方法传入的第一个参数是数据表的单数形式,怎么理解呢?例如这里传入的是website其实是模型名,数据表默认是websites这样的复数形式,这种约定我在Laravel中也碰见过,

也就是常说的,约定大于定义,也就是说,如果我们都按照约定的规范去开发,那么效率其实比重新定义,要高很多。

那么,定义好了模型,该怎么进行使用呢?

(async () => {
 let demo = await Website.create({
  url:'http://www.xxxx.com/',
  title:'demo'
 });
 console.log(demo);
})();

继承Model

const {Sequelize, DataTypes, Model} = require('sequelize');
const config = require('../config');

const sequelize = new Sequelize(config.database, config.username, config.password, {
 host: config.host,
 dialect: 'mysql',
 pool: {
  max: 5,
  min: 0,
  idle: 30000
 }
});

/**
 * @author chaojilaji
 * 数据表websites的关系对象映射
 */
class WebSite extends Model {

}

WebSite.init({
 id: {
  type: Sequelize.BIGINT,
  primaryKey: true,
  autoIncrement: true
 },
 url: Sequelize.STRING(255),
 title: Sequelize.STRING(255),
 status: Sequelize.INTEGER,
 delete_mark: Sequelize.BOOLEAN
}, {
 sequelize,
 modelName: 'Website',
 timestamps:false
});

(async () => {
 await sequelize.sync();
 let x = await WebSite.create({
  url: 'http://www.xxxxxxxx.com/',
  title: 'demo2'
 });
 console.log(x);
})();

module.exports = WebSite;

我比较推荐使用继承Model这种方式,通过创建一个class,这样可以使用model.exports=模块名的方式,将该模型封装起来。供别的地方使用,只需要require进去即可。

具体如何对数据表进行操作,就比较简单了,只需要参考API即可。 sequelize文档地址

富贵资源网 Design By www.hznty.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
富贵资源网 Design By www.hznty.com