Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
244 views
in Technique[技术] by (71.8m points)

javascript - how to declare a foreign key in a model in sequelize

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The associations in sequelize are well explained here : https://sequelize.org/master/manual/assocs.html


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...