MySQL 如何让 Sequelize 使用单数表名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21114499/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make Sequelize use singular table names
提问by Luis Carlos Chavarría
I have an model called User but Sequelize looks for the table USERS whenever I am trying to save in the DB. Does anyone know how to set Sequelize to use singular table names? Thanks.
我有一个名为 User 的模型,但是每当我尝试保存在数据库中时,Sequelize 都会查找表 USERS。有谁知道如何将 Sequelize 设置为使用单数表名?谢谢。
回答by Luis Carlos Chavarría
The docsstate that you can use the property freezeTableName.
该文件指出,你可以使用属性freezeTableName。
Please take a look at this example:
请看一下这个例子:
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'
})
回答by d512
While the accepted answer is correct, you can do this once for all tables rather than having to do it separately for each one. You simply pass in a similar options object into the Sequelize constructor, like so:
虽然接受的答案是正确的,但您可以对所有表执行一次,而不必为每个表单独执行。您只需将类似的选项对象传入 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)
Now when you define your entities, you don't have to specify freezeTableName: true:
现在,当您定义实体时,您不必指定freezeTableName: true:
var Project = sequelize.define('Project', {
title: Sequelize.STRING,
description: Sequelize.TEXT
})

