更改模型的 table 名称运行时
Change model's table name runtime
我正在使用 Sequelize.js,需要将历史数据保存到特定年份,并希望按年份前缀分隔我的 table
例如 prices_2010、prices_2011
我可以这样创造
tableName:"company_historical_" + new Date().getFullYear();
当前年份 table 并且它将使用此名称用于 table,但是如果我想存储或查询 2015 年的数据并且想使用模型而不是原始查询怎么办。
那么如何更改使用运行时的table。
类似于 changeTable()
方法 sequelize.
你永远不应该存储任何类型的信息,比如年份作为 table 名称,因为它的数据。您应该将它们存储为单独的 table 条目,作为实际可用数据。
将 company_historical_<year>
更改为仅 company_historical
并创建一个名为 company_historical_years
的新 table,其中仅包含 Company Historical[=] 的所有可能年份34=]条目可以有。
然后在 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
条目。
如果这些都没有意义,请随时发表评论并提出任何问题。
我正在使用 Sequelize.js,需要将历史数据保存到特定年份,并希望按年份前缀分隔我的 table 例如 prices_2010、prices_2011 我可以这样创造
tableName:"company_historical_" + new Date().getFullYear();
当前年份 table 并且它将使用此名称用于 table,但是如果我想存储或查询 2015 年的数据并且想使用模型而不是原始查询怎么办。
那么如何更改使用运行时的table。
类似于 changeTable()
方法 sequelize.
你永远不应该存储任何类型的信息,比如年份作为 table 名称,因为它的数据。您应该将它们存储为单独的 table 条目,作为实际可用数据。
将 company_historical_<year>
更改为仅 company_historical
并创建一个名为 company_historical_years
的新 table,其中仅包含 Company Historical[=] 的所有可能年份34=]条目可以有。
然后在 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
条目。
如果这些都没有意义,请随时发表评论并提出任何问题。