mysql 如何使Sequelize使用单数表名

k97glaaz  于 12个月前  发布在  Mysql
关注(0)|答案(4)|浏览(97)

我有一个名为User的模型,但每当我试图在DB中保存时,Sequelize都会查找表USERS。有谁知道如何设置Sequelize使用单数表名?谢谢。

p4tfgftt

p4tfgftt1#

文档说明您可以使用属性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'
})
x33g5p2x

x33g5p2x2#

虽然接受的答案是正确的,但您可以对所有表执行一次此操作,而不必对每个表单独执行此操作。你只需将一个类似的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
})
kcwpcxri

kcwpcxri3#

您可以直接执行它,而不是像下面这样在每个表中指定一次

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

ztmd8pv5

ztmd8pv54#

如果你需要为单数和复数定义使用不同的模型名称,你可以在模型的选项中传递name作为参数。
请看这个例子:

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

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

相关问题