javascript - 更改模型的表名运行时

标签 javascript mysql database sequelize.js database-partitioning

我正在使用 Sequelize.js 并且需要将历史数据保存到特定年份并且想按年份前缀分隔我的表 例如 prices_2010、prices_2011 我可以这样创造

tableName:"company_historical_" + new Date().getFullYear();

对于当前年份的表,它会将此名称用于表,但是如果我想存储或查询 2015 年的数据并且想使用模型而不是原始查询怎么办。 那么如何更改使用运行时表。 类似于 changeTable() 方法 sequelize。

最佳答案

你永远不应该存储任何类型的信息,比如年份作为数据的表名。您应该将它们存储为单独的表条目,作为实际可用的数据。

更改 company_historical_<year>只是company_historical并创建一个名为 company_historical_years 的新表其中只有 Company Historical 条目可以包含的所有可能年份。

然后在 Company Historical 条目和相关的 Company Historcal Years 条目之间建立关系。

所以像这样:

var CompanyHistoricalYears = sequelize.define('company_historical_years', {
    year: {
        type: Sequelize.INTEGER
    },
    classMethods: {
        associate: function (models) {
            CompanyHistoricalYears.hasMany(models.CompanyHistorical);
        }
    }
};


var CompanyHistorical = sequelize.define('company_historical', {
    ...
    classMethods: {
        associate: function (models) {
            CompanyHistorical.belongsTo(models.CompanyHistoricalYears);
        }
    }
};

然后你可以查询它:

CompanyHistoricalYears.findOne({
    where: {
        year: 2011, // or you can use "new Date().getFullYear()"
    },
    include: [CompanyHistorical]
});

这会给你一个 CompanyHistoricalYears条目和所有CompanyHistorical那一年内的条目。

如果这些都不合理,请随时提出任何问题。

关于javascript - 更改模型的表名运行时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40307333/

相关文章:

database - 如何将数据库条目加载到我的 Scala 模板中?

java - 自动分配ID号

javascript - JS : function waiting by calling itself with settimout - how to handle parmeters?

javascript - UI5 - 过滤器组合框放置问题

MySQL 查询以查找 ID = X 的值,如果 X 不存在则回退到 ID = 0

sql - 在 wamp 中运行 8mb 的 sql 代码?

database - 数据库连接中带有 OpenforwardOnly 标志的 Oracle 客户端。

javascript数组循环创建元素

javascript - 支持 Latex 标记的 AngularJs 编辑器

mysql - SQL - 如何根据另一个值的最大值选择一个值?