Here is an example of how I structure my Store.ts file:
import {DataTypes, Model, ModelAttributes} from "sequelize";
export default class Store extends Model {
declare id: number
declare name: string
declare phone: string
}
export const StoreFields: ModelAttributes = {
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true,
},
name: {
type: DataTypes.CHAR,
allowNull: false,
},
phone: {
type: DataTypes.CHAR,
}
}
In a similar fashion, here is my Item.ts file setup:
import {DataTypes, Model, ModelAttributes} from "sequelize";
export default class Item extends Model {
declare id: number
declare name: string
declare price: number
}
export const ItemFields: ModelAttributes = {
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true,
},
name: {
type: DataTypes.CHAR,
allowNull: false,
},
price: {
type: DataTypes.INTEGER,
allowNull: false,
},
storeid: {
type: DataTypes.INTEGER,
allowNull: false,
references: {
model: 'Store',
key: 'id',
},
onDelete: 'CASCADE'
}
}
To initialize these models, I use the following approach:
import {DataTypes, Model, ModelAttributes, ModelStatic, Sequelize} from "sequelize";
import Item, {ItemFields} from "./models/Item.js";
import Store, {StoreFields} from "./models/Store.js";
export const sequelize = new Sequelize(process.env.PGURL, {dialect: "postgres"});
void Item.init(ItemFields, {sequelize, timestamps: false, tableName: 'item', modelName: 'item'}).sync()
void Store.init(StoreFields, {sequelize, timestamps: false, tableName: 'store', modelName: 'store'}).sync()
Store.hasMany(Item, {
foreignKey: "storeid",
})
Item.belongsTo(Store, {
foreignKey: "storeid",
})
The issue arises when I run
Store.create({name: "test", phone: "testphone"})
as the model ends up with extra spaces at the end.
Please see the image link below for reference:
https://i.sstatic.net/gbAnG.pngIt's worth noting that there may be missing quotes in response.data.rows