我想将学生数据存储在postgres中,如下所示: 卷号应根据批次自动增加。
我想知道如何在Sequelize中实现这一点。
id batch rollno name
---------------------------------------------------------------
1 A 1000 John
2 A 1001 Javed
3 A 1002 Jake
4 B 1000 Jose
5 B 1001 James
6 A 1003 Jerry
这是我创建的模型。
var Student = sequelize.define('student', {
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
batch: {
type: DataTypes.STRING,
allowNull: false,
},
rollno: {
type: DataTypes.INTEGER(11),
allowNull: true,
autoIncrement: true,
},
name: {
type: DataTypes.STRING,
allowNull: true,
}
};
答案 0 :(得分:0)
您不能使用常规的自动递增方式执行此操作,因为这将要求每个批次使用不同的顺序。您可以通过编写一个在插入时触发并在表中查询该批处理中当前最大rollno并添加1的触发器来做到这一点,但这可能不是一个好主意。
相反,您可以做的是在运行查询时计算rollno:
CREATE TABLE test (
id serial,
batch text
);
INSERT INTO test (batch) VALUES ('A');
SELECT
id,
batch,
999 + rank() OVER (PARTITION BY batch order by id) as rollno
FROM test
order by id