前置条件
安装sequelize
npm install -g sequelize-auto
安装对应数据库包,比如pg
npm install pg
如果项目采用的是pnpm安装的包,可以将添加一个全局的pg,主要做自动模型生成
npm install -g pg
sqlite安装
//安装
npm install -g sequelize-auto sqlite3
//获取模型
sequelize-auto -d zhiying.db -o ./electron/data/models --dialect sqlite
当前项目需要包安装
npm install pg
npm install sequelize
生成模型
sequelize-auto -o "./models" -d wafwagdata -h 172.18.100.21 -u venuspostgres -p 5432 -x xxx -e postgres
sequelize-auto -o 模型位置 -d 数据库 -h 服务器ip -u 用户名 -p 端口 -x 密码 -e 数据库类型
模型修改
import { DataTypes, Model } from 'sequelize';
import sequelize from '@/config/database';
class UrlStat extends Model {}
UrlStat.init(
{
url: {
type: DataTypes.TEXT,
allowNull: true,
comment: 'URL',
field: 'url'
},
servIp: {
type: DataTypes.TEXT,
field: 'serv_ip',
allowNull: true,
comment: '服务端IP'
},
domain: {
type: DataTypes.TEXT,
allowNull: true,
comment: '域名'
},
timeint: {
type: DataTypes.BIGINT,
allowNull: true,
comment: '时间戳'
},
visitCount: {
type: DataTypes.INTEGER,
field: 'visit_count',
allowNull: true,
comment: '访问量'
},
avgDelay: {
type: DataTypes.INTEGER,
allowNull: true,
field: 'avg_delay',
comment: '平均延时'
}
},
{
sequelize,
tableName: 'url_stat',
modelName: 'UrlStat',
schema: 'public',
timestamps: false
}
);
export default UrlStat;
database配置文件:
import Sequelize from 'sequelize';
export default new Sequelize(global.config.db.wag.database, global.config.db.wag.user, global.config.db.wag.password, {
host: global.config.db.wag.host,
port: global.config.db.wag.port,
dialect: 'postgres',
operatorsAliases: false,
logging: true, // 日志输出
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 1000
}
});
查询测试
UrlStat.findOne({
attributes: {
exclude: ['id'] // 要排除的字段名称,这里是 'id' 由于公司这张表没有主键没有id,所以必须排除,不然会报错
},
where: { url: 'blog.csdn.net' }
}).then((item) => {
console.log(item);
console.log('===========');
});