How to configure a one to many relationship in Sequelize?





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







2















I'm currently using Express with Sequelize + MySQL and was wondering what the best approach for me to solve this problem was. I apologise if this is a basic question as I'm pretty new to Sequelize and even SQL databases in general.



I have a model User like so;



export default db.define('User', {
id: {
type: Sequelize.INTEGER,
allowNull: false,
primaryKey: true,
autoIncrement: true,
},
name: {
type: Sequelize.STRING,
allowNull: false,
},
email: {
type: Sequelize.STRING,
allowNull: false,
},
createdAt: {
type: Sequelize.DATE,
defaultValue: Sequelize.NOW,
},
updatedAt: {
type: Sequelize.DATE,
defaultValue: Sequelize.NOW,
},
});


Then I also have another model Shoe like so;



export default db.define('Shoe', {
id: {
type: Sequelize.INTEGER,
allowNull: false,
primaryKey: true,
autoIncrement: true,
},
name: {
type: Sequelize.STRING,
allowNull: false,
},
size: {
type: Sequelize.INTEGER,
allowNull: true,
},
quality: {
type: Sequelize.ENUM('Brand New', 'Used', 'Collector Item'),
allowNull: false,
},
createdAt: {
type: Sequelize.DATE,
defaultValue: Sequelize.NOW,
},
updatedAt: {
type: Sequelize.DATE,
defaultValue: Sequelize.NOW,
},
});


I then define an association between these two.



User.hasMany(Shoe);
Shoe.belongsTo(User);


However, the problem with this is that it 'creates' the shoe and this leads to duplication. I basically want a table called "Shoes" that has the shoes in it, and then the user just references the ids based on what shoes it has.



Not sure what the best way to do this is, especially if a user owns multiple shoes. In pseudo I suppose I'd want something like an array of shoe id's such as shoes: [1, 2, 3, 4] that when queried then get looked up in the shoes table somehow and inserted into the User response.



Obviously I can do something like that in raw SQL, but I figure there must be a better way to approach this given how much power Sequelize has.



Hopefully someone can provide some advice and help regarding this!










share|improve this question





























    2















    I'm currently using Express with Sequelize + MySQL and was wondering what the best approach for me to solve this problem was. I apologise if this is a basic question as I'm pretty new to Sequelize and even SQL databases in general.



    I have a model User like so;



    export default db.define('User', {
    id: {
    type: Sequelize.INTEGER,
    allowNull: false,
    primaryKey: true,
    autoIncrement: true,
    },
    name: {
    type: Sequelize.STRING,
    allowNull: false,
    },
    email: {
    type: Sequelize.STRING,
    allowNull: false,
    },
    createdAt: {
    type: Sequelize.DATE,
    defaultValue: Sequelize.NOW,
    },
    updatedAt: {
    type: Sequelize.DATE,
    defaultValue: Sequelize.NOW,
    },
    });


    Then I also have another model Shoe like so;



    export default db.define('Shoe', {
    id: {
    type: Sequelize.INTEGER,
    allowNull: false,
    primaryKey: true,
    autoIncrement: true,
    },
    name: {
    type: Sequelize.STRING,
    allowNull: false,
    },
    size: {
    type: Sequelize.INTEGER,
    allowNull: true,
    },
    quality: {
    type: Sequelize.ENUM('Brand New', 'Used', 'Collector Item'),
    allowNull: false,
    },
    createdAt: {
    type: Sequelize.DATE,
    defaultValue: Sequelize.NOW,
    },
    updatedAt: {
    type: Sequelize.DATE,
    defaultValue: Sequelize.NOW,
    },
    });


    I then define an association between these two.



    User.hasMany(Shoe);
    Shoe.belongsTo(User);


    However, the problem with this is that it 'creates' the shoe and this leads to duplication. I basically want a table called "Shoes" that has the shoes in it, and then the user just references the ids based on what shoes it has.



    Not sure what the best way to do this is, especially if a user owns multiple shoes. In pseudo I suppose I'd want something like an array of shoe id's such as shoes: [1, 2, 3, 4] that when queried then get looked up in the shoes table somehow and inserted into the User response.



    Obviously I can do something like that in raw SQL, but I figure there must be a better way to approach this given how much power Sequelize has.



    Hopefully someone can provide some advice and help regarding this!










    share|improve this question

























      2












      2








      2








      I'm currently using Express with Sequelize + MySQL and was wondering what the best approach for me to solve this problem was. I apologise if this is a basic question as I'm pretty new to Sequelize and even SQL databases in general.



      I have a model User like so;



      export default db.define('User', {
      id: {
      type: Sequelize.INTEGER,
      allowNull: false,
      primaryKey: true,
      autoIncrement: true,
      },
      name: {
      type: Sequelize.STRING,
      allowNull: false,
      },
      email: {
      type: Sequelize.STRING,
      allowNull: false,
      },
      createdAt: {
      type: Sequelize.DATE,
      defaultValue: Sequelize.NOW,
      },
      updatedAt: {
      type: Sequelize.DATE,
      defaultValue: Sequelize.NOW,
      },
      });


      Then I also have another model Shoe like so;



      export default db.define('Shoe', {
      id: {
      type: Sequelize.INTEGER,
      allowNull: false,
      primaryKey: true,
      autoIncrement: true,
      },
      name: {
      type: Sequelize.STRING,
      allowNull: false,
      },
      size: {
      type: Sequelize.INTEGER,
      allowNull: true,
      },
      quality: {
      type: Sequelize.ENUM('Brand New', 'Used', 'Collector Item'),
      allowNull: false,
      },
      createdAt: {
      type: Sequelize.DATE,
      defaultValue: Sequelize.NOW,
      },
      updatedAt: {
      type: Sequelize.DATE,
      defaultValue: Sequelize.NOW,
      },
      });


      I then define an association between these two.



      User.hasMany(Shoe);
      Shoe.belongsTo(User);


      However, the problem with this is that it 'creates' the shoe and this leads to duplication. I basically want a table called "Shoes" that has the shoes in it, and then the user just references the ids based on what shoes it has.



      Not sure what the best way to do this is, especially if a user owns multiple shoes. In pseudo I suppose I'd want something like an array of shoe id's such as shoes: [1, 2, 3, 4] that when queried then get looked up in the shoes table somehow and inserted into the User response.



      Obviously I can do something like that in raw SQL, but I figure there must be a better way to approach this given how much power Sequelize has.



      Hopefully someone can provide some advice and help regarding this!










      share|improve this question














      I'm currently using Express with Sequelize + MySQL and was wondering what the best approach for me to solve this problem was. I apologise if this is a basic question as I'm pretty new to Sequelize and even SQL databases in general.



      I have a model User like so;



      export default db.define('User', {
      id: {
      type: Sequelize.INTEGER,
      allowNull: false,
      primaryKey: true,
      autoIncrement: true,
      },
      name: {
      type: Sequelize.STRING,
      allowNull: false,
      },
      email: {
      type: Sequelize.STRING,
      allowNull: false,
      },
      createdAt: {
      type: Sequelize.DATE,
      defaultValue: Sequelize.NOW,
      },
      updatedAt: {
      type: Sequelize.DATE,
      defaultValue: Sequelize.NOW,
      },
      });


      Then I also have another model Shoe like so;



      export default db.define('Shoe', {
      id: {
      type: Sequelize.INTEGER,
      allowNull: false,
      primaryKey: true,
      autoIncrement: true,
      },
      name: {
      type: Sequelize.STRING,
      allowNull: false,
      },
      size: {
      type: Sequelize.INTEGER,
      allowNull: true,
      },
      quality: {
      type: Sequelize.ENUM('Brand New', 'Used', 'Collector Item'),
      allowNull: false,
      },
      createdAt: {
      type: Sequelize.DATE,
      defaultValue: Sequelize.NOW,
      },
      updatedAt: {
      type: Sequelize.DATE,
      defaultValue: Sequelize.NOW,
      },
      });


      I then define an association between these two.



      User.hasMany(Shoe);
      Shoe.belongsTo(User);


      However, the problem with this is that it 'creates' the shoe and this leads to duplication. I basically want a table called "Shoes" that has the shoes in it, and then the user just references the ids based on what shoes it has.



      Not sure what the best way to do this is, especially if a user owns multiple shoes. In pseudo I suppose I'd want something like an array of shoe id's such as shoes: [1, 2, 3, 4] that when queried then get looked up in the shoes table somehow and inserted into the User response.



      Obviously I can do something like that in raw SQL, but I figure there must be a better way to approach this given how much power Sequelize has.



      Hopefully someone can provide some advice and help regarding this!







      mysql node.js express sequelize.js






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 24 '18 at 5:08









      BorassignBorassign

      1128




      1128
























          1 Answer
          1






          active

          oldest

          votes


















          3















          1. I recommend use tableName option.


          2. If you want store Users, Shoes and info about what shoe each user have, you need create third table. This n:m association, because each user may have several shoes, and each shoe may belongs to several users. You can create this table by several ways:





            • see Model.belongsToMany tutorial and api doc



              User.belongsToMany(Shoe, {through: 'UserShoe'});
              Shoe.belongsToMany(User, {through: 'UserShoe'});



            • define UserShoe model and then associate User, Shoe and UserShoe models:



              export default db.define('UserShoe', {
              userId: {
              type: Sequelize.INTEGER,
              allowNull: false,
              primaryKey: true
              },
              shoeId: {
              type: Sequelize.INTEGER,
              allowNull: false,
              primaryKey: true
              }
              });


              User.belongsToMany(Shoe, {through: UserShoe});
              Shoe.belongsToMany(User, {through: UserShoe});



            • or like this:



              User.hasMany(UserShoe);
              UserShoe.belongsTo(User);
              Shoe.hasMany(UserShoe);
              UserShoe.belongsTo(Shoe);




          3. I recommend you read a book SQL antipatterns / Karwin Bill. Raleigh and Sequelize association docs.






          share|improve this answer
























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53455341%2fhow-to-configure-a-one-to-many-relationship-in-sequelize%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            3















            1. I recommend use tableName option.


            2. If you want store Users, Shoes and info about what shoe each user have, you need create third table. This n:m association, because each user may have several shoes, and each shoe may belongs to several users. You can create this table by several ways:





              • see Model.belongsToMany tutorial and api doc



                User.belongsToMany(Shoe, {through: 'UserShoe'});
                Shoe.belongsToMany(User, {through: 'UserShoe'});



              • define UserShoe model and then associate User, Shoe and UserShoe models:



                export default db.define('UserShoe', {
                userId: {
                type: Sequelize.INTEGER,
                allowNull: false,
                primaryKey: true
                },
                shoeId: {
                type: Sequelize.INTEGER,
                allowNull: false,
                primaryKey: true
                }
                });


                User.belongsToMany(Shoe, {through: UserShoe});
                Shoe.belongsToMany(User, {through: UserShoe});



              • or like this:



                User.hasMany(UserShoe);
                UserShoe.belongsTo(User);
                Shoe.hasMany(UserShoe);
                UserShoe.belongsTo(Shoe);




            3. I recommend you read a book SQL antipatterns / Karwin Bill. Raleigh and Sequelize association docs.






            share|improve this answer




























              3















              1. I recommend use tableName option.


              2. If you want store Users, Shoes and info about what shoe each user have, you need create third table. This n:m association, because each user may have several shoes, and each shoe may belongs to several users. You can create this table by several ways:





                • see Model.belongsToMany tutorial and api doc



                  User.belongsToMany(Shoe, {through: 'UserShoe'});
                  Shoe.belongsToMany(User, {through: 'UserShoe'});



                • define UserShoe model and then associate User, Shoe and UserShoe models:



                  export default db.define('UserShoe', {
                  userId: {
                  type: Sequelize.INTEGER,
                  allowNull: false,
                  primaryKey: true
                  },
                  shoeId: {
                  type: Sequelize.INTEGER,
                  allowNull: false,
                  primaryKey: true
                  }
                  });


                  User.belongsToMany(Shoe, {through: UserShoe});
                  Shoe.belongsToMany(User, {through: UserShoe});



                • or like this:



                  User.hasMany(UserShoe);
                  UserShoe.belongsTo(User);
                  Shoe.hasMany(UserShoe);
                  UserShoe.belongsTo(Shoe);




              3. I recommend you read a book SQL antipatterns / Karwin Bill. Raleigh and Sequelize association docs.






              share|improve this answer


























                3












                3








                3








                1. I recommend use tableName option.


                2. If you want store Users, Shoes and info about what shoe each user have, you need create third table. This n:m association, because each user may have several shoes, and each shoe may belongs to several users. You can create this table by several ways:





                  • see Model.belongsToMany tutorial and api doc



                    User.belongsToMany(Shoe, {through: 'UserShoe'});
                    Shoe.belongsToMany(User, {through: 'UserShoe'});



                  • define UserShoe model and then associate User, Shoe and UserShoe models:



                    export default db.define('UserShoe', {
                    userId: {
                    type: Sequelize.INTEGER,
                    allowNull: false,
                    primaryKey: true
                    },
                    shoeId: {
                    type: Sequelize.INTEGER,
                    allowNull: false,
                    primaryKey: true
                    }
                    });


                    User.belongsToMany(Shoe, {through: UserShoe});
                    Shoe.belongsToMany(User, {through: UserShoe});



                  • or like this:



                    User.hasMany(UserShoe);
                    UserShoe.belongsTo(User);
                    Shoe.hasMany(UserShoe);
                    UserShoe.belongsTo(Shoe);




                3. I recommend you read a book SQL antipatterns / Karwin Bill. Raleigh and Sequelize association docs.






                share|improve this answer














                1. I recommend use tableName option.


                2. If you want store Users, Shoes and info about what shoe each user have, you need create third table. This n:m association, because each user may have several shoes, and each shoe may belongs to several users. You can create this table by several ways:





                  • see Model.belongsToMany tutorial and api doc



                    User.belongsToMany(Shoe, {through: 'UserShoe'});
                    Shoe.belongsToMany(User, {through: 'UserShoe'});



                  • define UserShoe model and then associate User, Shoe and UserShoe models:



                    export default db.define('UserShoe', {
                    userId: {
                    type: Sequelize.INTEGER,
                    allowNull: false,
                    primaryKey: true
                    },
                    shoeId: {
                    type: Sequelize.INTEGER,
                    allowNull: false,
                    primaryKey: true
                    }
                    });


                    User.belongsToMany(Shoe, {through: UserShoe});
                    Shoe.belongsToMany(User, {through: UserShoe});



                  • or like this:



                    User.hasMany(UserShoe);
                    UserShoe.belongsTo(User);
                    Shoe.hasMany(UserShoe);
                    UserShoe.belongsTo(Shoe);




                3. I recommend you read a book SQL antipatterns / Karwin Bill. Raleigh and Sequelize association docs.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 30 '18 at 20:31









                FarisFaris

                1164




                1164
































                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53455341%2fhow-to-configure-a-one-to-many-relationship-in-sequelize%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    這個網誌中的熱門文章

                    Academy of Television Arts & Sciences

                    L'Équipe

                    1995 France bombings