如何使 Sequelize 使用单数表名

我有一个模型称为用户,但 Sequelize 寻找表 USERS 每当我试图保存在数据库。有人知道如何将 Sequelize 设置为使用单数表名吗?谢谢。

106437 次浏览

可以使用属性 freezeTableName医生状态。

请看这个例子:

var Bar = sequelize.define('Bar', { /* bla */ }, {
// don't add the timestamp attributes (updatedAt, createdAt)
timestamps: false,


// don't delete database entries but set the newly added attribute deletedAt
// to the current date (when deletion was done). paranoid will only work if
// timestamps are enabled
paranoid: true,


// don't use camelcase for automatically added attributes but underscore style
// so updatedAt will be updated_at
underscored: true,


// disable the modification of tablenames; By default, sequelize will automatically
// transform all passed model names (first parameter of define) into plural.
// if you don't want that, set the following
freezeTableName: true,


// define the table's name
tableName: 'my_very_custom_table_name'
})

虽然接受的答案是正确的,但您可以对所有表执行一次,而不必为每个表单独执行。您只需将一个类似的 options 对象传入 Sequelize 构造函数,如下所示:

var Sequelize = require('sequelize');


//database wide options
var opts = {
define: {
//prevent sequelize from pluralizing table names
freezeTableName: true
}
}


var sequelize = new Sequelize('mysql://root:123abc@localhost:3306/mydatabase', opts)

现在,当您定义实体时,您不必指定 freezeTableName: true:

var Project = sequelize.define('Project', {
title: Sequelize.STRING,
description: Sequelize.TEXT
})

如果需要为单数和复数定义使用不同的模型名称,可以在模型选项中将名称作为参数传递。

请看这个例子:

    const People = sequelize.define('people', {
name: DataTypes.STRING,
}, {
hooks: {
beforeCount (options) {
options.raw = true;
}
},
tableName: 'people',
name: {
singular: 'person',
plural: 'people'
}
});

当一条记录被查询时,这将返回“ person”作为对象,当我们获取多条记录时,返回“ people”作为数组。

可以直接执行,而不必在每个表中指定一次 比如下面

var db_instance = new Sequelize(config.DB.database, config.DB.username, config.DB.password, {
host: config.DB.host,
dialect: config.DB.dialect,
define: {
timestamps: true,
freezeTableName: true
},
logging: false
});


或者

您也可以直接告诉 Sequelize 表的名称:

sequelize.define('User', {
// ... (attributes)
}, {
tableName: 'Employees'
});

您可以在 Sequelize.js 的文档中看到这两个方法

freezeTableName相关的 Sequelize.js 的文件