首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使Sequelize使用单表名称

如何使Sequelize使用单表名称
EN

Stack Overflow用户
提问于 2014-01-14 21:15:50
回答 3查看 89.7K关注 0票数 125

我有一个名为User的模型,但是Sequelize会在我试图保存到数据库中时查找表USERS。有人知道如何设置Sequelize来使用单表名称吗?谢谢。

EN

回答 3

Stack Overflow用户

发布于 2014-04-21 04:25:21

可以使用属性freezeTableNamedocs状态。

请看下面的示例:

代码语言:javascript
复制
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'
})
票数 262
EN

Stack Overflow用户

发布于 2016-01-02 02:30:42

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

代码语言:javascript
复制
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

代码语言:javascript
复制
var Project = sequelize.define('Project', {
    title: Sequelize.STRING,
    description: Sequelize.TEXT
})
票数 109
EN

Stack Overflow用户

发布于 2020-08-10 15:28:31

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

请看下面的示例:

代码语言:javascript
复制
    const People = sequelize.define('people', {
    name: DataTypes.STRING,
}, {
    hooks: {
        beforeCount (options) {
            options.raw = true;
        }
    },
    tableName: 'people',
    name: {
        singular: 'person',
        plural: 'people'
    }
});

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

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21114499

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档