Change model's table name runtime

那年仲夏 提交于 2019-12-24 06:35:06

问题


I am using Sequelize.js and need to save historical data till specific year and want to separate my tables by year's prefix for example prices_2010, prices_2011 e.g. I can create so

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

for current years table and it will use this name for table, but what if I want to store or query data of 2015 year and want to use models instead of raw queries. So how can I change table of use runtime. something like changeTable() method sequelize.


回答1:


You should never store any kind of information like years as table names since its data. You should store them as separate table entries, as actual usable data.

Change company_historical_<year> to just company_historical and create a new table called company_historical_years which just has all the possible years the Company Historical entries can have.

Then create a relationship between the Company Historical entry and the related Company Historcal Years entry.

So something like:

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);
        }
    }
};

and then you can query it with:

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

this will give you a single CompanyHistoricalYears entry and all the CompanyHistorical entries that are within that year.

If non of this makes sense then feel free to comment with any questions.



来源:https://stackoverflow.com/questions/40307333/change-models-table-name-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!