更改模型的表名运行时 [英] Change model's table name runtime

查看:71
本文介绍了更改模型的表名运行时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

对于当前年表,它将使用该名称作为表,但是如果我要存储或查询2015年的数据并希望使用模型而不是原始查询该怎么办. 因此,如何更改使用时间表. 类似于changeTable()方法的续集.

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.

推荐答案

自数据以来,切勿将任何类型的信息(如年份)存储为表名.您应该将它们存储为单独的表条目,作为实际的可用数据.

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.

company_historical_<year>更改为company_historical,并创建一个名为company_historical_years的新表,该表具有公司历史条目可以拥有的所有可能年份.

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.

类似这样:

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

这将为您提供一个CompanyHistoricalYears条目以及该年内的所有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.

这篇关于更改模型的表名运行时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆