I have a model called video.js.
module.exports= function(sequelize, DataTypes){
return sequelize.define(
"video",
{
id:{
type:DataTypes.INTEGER(11).UNSIGNED,
allowNull:false,
autoIncrement:true,
primaryKey:true,
field:"id"
},
title:{
type:DataTypes.STRING(20),
unique:true,
field:"title"
},
createdAt: {
type: DataTypes.DATE,
allowNull: true,
field: "createdAt"
},
updatedAt: {
type: DataTypes.DATE,
allowNull: true,
field: "updatedAt"
}
},
{
tableName:"video"
}
);
};
I have created a table equivalent of this model in mysql and I have added a foreign key that is being used in another table called user.
This is the model for the user table.
module.exports = function(sequelize, DataTypes) {
return sequelize.define(
"user",
{
id: {
type: DataTypes.INTEGER(11).UNSIGNED,
allowNull: false,
primaryKey: true,
autoIncrement: true,
field: "id"
},
firstName: {
type: DataTypes.STRING(255),
allowNull: false,
defaultValue: "",
field: "firstName"
},
lastName: {
type: DataTypes.STRING(255),
allowNull: false,
defaultValue: "",
field: "lastName"
},
},
{
tableName: "user"
}
);
};
I have used the id column in the user table as a foreign key in the video table with a one to many relationship where one user has one or many videos. The problem I am facing is i do not know how to define a model with a foreign key.
CREATE TABLE `video` (`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL DEFAULT '',
`createdAt` datetime DEFAULT NULL,
`updatedAt` datetime DEFAULT NULL,
PRIMARY KEY(`id`),
FOREIGN KEY (userId_FK) REFERENCES user(id));
How do I create an equivalent of this video table as a model in sequelize?
question from:
https://stackoverflow.com/questions/65873157/how-to-declare-a-foreign-key-in-a-model-in-sequelize