在处理 mysql 数据库时,我正在使用sequelize-cli 迁移。
如果我输入命令
sequelize init
创建了两个文件夹models
和migrations
此外,例如,如果我在两个模型之间设置关联
User.hasMany(Posts)
我必须手动将外键添加到迁移文件中。
(但不是模型文件,对吧?)
此外,迁移文件中还有诸如created_at、updated_at之类的列
但不在模型文件中。
当使用db.sync();
时,没有这样的迁移文件,因此我不必手动为模型文件添加外键。
我知道迁移文件仅与数据库表架构有关,但是模型文件实际上在做什么......?
该模型文件与数据库表无关吗?
我了解同步和迁移之间的区别,(如果要设置force:true但不设置迁移,则同步删除所有表)
但也许我无法理解内部发生的事情(迁移之间的模型)
如有任何建议,我们将不胜感激!
最佳答案
当您使用sequelize-cli时,已经为您创建了createdAt和updatedAt列,因为sequelize使用它们来更新表。您可以禁用它们。
sequelize 模型文件不需要createdAt 和updatedAt 来定义更改,因为它们是由sequelize 完成的。
您必须手动将外键添加到迁移文件和模型中。 模型文件是您的sequelize与数据库架构交互的引用。
它为您的 Sequelize 设置参数以触发对数据库的查询。 您可以说迁移文件与您的数据库架构有关,而模型文件与您的数据库中存储的数据有关。
示例考虑用户表及其基本信息。
用户模型
module.exports = (sequelize, DataTypes) => {
var Users = sequelize.define('users', {
user_id: {
type: DataTypes.STRING,
primaryKey: true,
},
}, {});
User.associate = function(models) {
Users.hasOne(models.basicinfo, {
foreignKey: 'user_id',
as: 'BasicInfo'
});
};
return Users;
};
基本信息型号
module.exports = (sequelize, DataTypes) => {
var basicinfo = sequelize.define('basicinfo', {
first_name: {
type: DataTypes.STRING,
},
last_name: {
type: DataTypes.STRING,
},
};{});
basicinfo.associate = function (models) {
basicinfo.belongsTo(models.users, {
foreignKey: 'user_id',
onDelete: 'CASCADE'
});
};
return basicinfo;
};
希望这能消除您的困惑,当您使用这个伟大的库时,您会学到更多。
这是我更新的答案,其中包含每个模型的迁移文件。
用户迁移
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('users', {
user_id: {
type: Sequelize.STRING,
primaryKey: true,
},
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('users');
}
};
基本信息迁移
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('basicinfo', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
user_id: {
type: Sequelize.STRING,
allowNull: false,
unique: true,
onDelete: 'CASCADE',
references: {
model: 'users',
key: 'user_id',
as: 'user_id'
}
},
profile_img: {
type: Sequelize.STRING
},
first_name: {
type: Sequelize.STRING,
},
last_name: {
type: Sequelize.STRING,
},
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('basicinfo');
}
};
关于mysql - 表达与迁移文件相比,模型文件实际上在做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50444226/