圆月山庄资源网 Design By www.vgjia.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文档地址

标签:
nodejs,Sequelize操作数据库,nodejs,Sequelize,数据库

圆月山庄资源网 Design By www.vgjia.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
圆月山庄资源网 Design By www.vgjia.com