如何创建表而不需要后缀-cli?我的项目是管理几个数据库文件,有时数据库将从头开始创建。我需要在数据库创建后写到它。使用sqlite3编写原始查询是一种选择,但我希望继续使用Sequelize。
我想要创建一个表的模型示例:
CarType.init(
{
id: {
type: DataTypes.STRING,
allowNull: false,
primaryKey: true
},
details: {
type: DataTypes.STRING,
},
},
{
sequelize,
tableName: 'CarType',
paranoid: true,
timestamps: true
}
);
....
Car.init(
{
id: {
type: DataTypes.STRING,
allowNull: false,
primaryKey: true
},
brand: {
type: DataTypes.STRING,
},
carType: {
type: DataTypes.STRING,
},
},
{
sequelize,
tableName: 'Car',
paranoid: true,
timestamps: true
}
);
/*
|---------------------------------------------------------------------------------------------------------------------------------
| SQL equivalent: CONSTRAINT carType_FK FOREIGN KEY (carType) REFERENCES CarType(id) ON DELETE RESTRICT ON UPDATE RESTRICT
|---------------------------------------------------------------------------------------------------------------------------------
*/
CarType.hasMany(Car, {
foreignKey: 'carType',
onDelete: 'RESTRICT',
onUpdate: 'RESTRICT',
})
Car.belongsTo(CarType, { foreignKey: 'carType', targetKey: 'id' });如何使用描述的后缀模型创建表(准备数据库)?
发布于 2022-11-19 15:05:25
经过一些研究,我发现我们只需要连接到数据库文件,然后再用已连接的后缀等价物连接到数据库文件,就可以得到如下模型:
const sequelize = await new Sequelize({
dialect: 'sqlite',
storage: dbPath,
logging: false,
});
/// for each model, init it with this sequelize method
Model.init(
{
column: {
type: DataTypes.STRING(128),
...options
},
},
{
sequelize,
tableName: 'Model',
...options
}
);为了达到我的目的,我创建了一些方法来初始化数据库上的每个模型,因此我可以控制许多数据库文件的创建和管理。
https://stackoverflow.com/questions/74475398
复制相似问题