nodejs使用Sequelize框架操作数据库

2020-10-29  本文已影响0人  chaojilaji

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文档地址

炒鸡辣鸡原创文章,转载请注明来源

上一篇下一篇

猜你喜欢

热点阅读