Search code examples
mysqlnode.jssequelize-cli

Foreign Key in Sequelize


I have three tables(models): Users,preferences,ideas. Users has a column 'username' as a primary key and I would like to add 'username' as foreign key to the other tables . How is it done in sequelize? I am a noob at sequelize ,so please do answer this. The hasMany,belongsTo were confusing to me. It would be really helpful if someone answers this.


Solution

  • For the two objects: User and Preference, you can specify the relationship as follows:

    const User = sequelize.define('User', {
            username: Sequelize.STRING,
    });
    
    const Preference = sequelize.define('Preference', {
        id: Sequelize.INTEGER,
        //Below, 'users' refer to the table name and 'username' is the primary key in the 'users' table
        user: {
           type: Sequelize.STRING,
           references: {
              model: 'users', 
              key: 'username', 
           }
        }
    });
    
    User.hasMany(Preference); // Add one to many relationship
    

    I would suggest to read the following document to understand better:

    Sequelize Foreign Key