问题描述
首先,我曾经使用 Django 作为 ORM 框架,而 django 为我处理一切……创建约束、表等……但是当我看到 sequelize 是一个 ORM 框架时,我决定放弃使用 Express 对一个项目进行更改。
到目前为止我正在使用迁移,但我可以看出这与 django 方式有很大不同,我可以使用 cli 生成一个模型和第一次迁移,但我想创建带有约束等的整个表,有是一种方法吗?或者函数“has”和“belong”只是从后端的角度验证数据,而不是真正在后端创建约束?
另外一件事是我真的必须使用迁移将所有工作做两次吗?我的意思是配置我的模型,然后配置迁移中的所有字段?
最后一件事,有没有办法清除数据库并重新运行迁移?如果没有迁移,我可以使用 sync({force:true}) 但这不适用于迁移。
'use strict'
const {
Model
} = require('sequelize')
module.exports = (sequelize,DataTypes) => {
class Foo extends Model {
static associate (models) {
models.Foo.belongsTo(models.Bar,{ foreignKey: 'foo_id' });
}
};
Foo.init({
id: {
type: DataTypes.INTEGER,primaryKey: true,autoIncrement: true
},name: {
type: DataTypes.STRING(100),allowNull: false,unique: true,},{
sequelize,modelName: 'foo'
})
return Foo
}
const {
Model
} = require('sequelize')
module.exports = (sequelize,DataTypes) => {
class Bar extends Model {
static associate (models) { }
};
Bar.init({
id: {
type: DataTypes.INTEGER,modelName: 'bar'
})
return Bar
}
迁移就像
'use strict';
module.exports = {
up: async (queryInterface,Sequelize) => {
await queryInterface.createTable('foo',{
id: {
type: Sequelize.DataTypes.INTEGER,name: {
type: Sequelize.DataTypes.STRING,})
},// How can i create my constraints here?
down: async (queryInterface,Sequelize) => {
await queryInterface.dropTable('foo')
}
};
module.exports = {
up: async (queryInterface,Sequelize) => {
await queryInterface.createTable('bar',foo_id: {
type: Sequelize.DataTypes.INTEGER,down: async (queryInterface,Sequelize) => {
await queryInterface.dropTable('bar')
}
};
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)