Sequelize: How to query model by 1:n association, but include all associated objects in a single query...











up vote
2
down vote

favorite
1












I have a Ticket model with hasMany relation to Approval model (multi-level approval workflow). Approval belongsTo a User.



For a particular use case, I'll have to filter all the pending approvals to be made by a User and show him his to be approved Tickets.



Have solved like so -



models.Ticket.findAll({
include: [{
model: models.Approval,
where: { userId: options.userId }
}]
}).then(function(tickets){...


Gives me the filtered tickets but I've to also get the list of all approvals for the ticket to show the approval workflow. Can this be done by a single query in Sequelize?



Data (T is Ticket, A is Approval and U is User) -

T1 - A1/U1, A2/U2, A3/U3
T2 - A4/U2
T3 - A5/U1, A6/U4

Output for U1 -

T1 - A1/U1
T3 - A5/U1

Expected for U1 -

T1 - A1/U1, A2/U2, A3/U3
T3 - A5/U1, A6/U4









share|improve this question




























    up vote
    2
    down vote

    favorite
    1












    I have a Ticket model with hasMany relation to Approval model (multi-level approval workflow). Approval belongsTo a User.



    For a particular use case, I'll have to filter all the pending approvals to be made by a User and show him his to be approved Tickets.



    Have solved like so -



    models.Ticket.findAll({
    include: [{
    model: models.Approval,
    where: { userId: options.userId }
    }]
    }).then(function(tickets){...


    Gives me the filtered tickets but I've to also get the list of all approvals for the ticket to show the approval workflow. Can this be done by a single query in Sequelize?



    Data (T is Ticket, A is Approval and U is User) -

    T1 - A1/U1, A2/U2, A3/U3
    T2 - A4/U2
    T3 - A5/U1, A6/U4

    Output for U1 -

    T1 - A1/U1
    T3 - A5/U1

    Expected for U1 -

    T1 - A1/U1, A2/U2, A3/U3
    T3 - A5/U1, A6/U4









    share|improve this question


























      up vote
      2
      down vote

      favorite
      1









      up vote
      2
      down vote

      favorite
      1






      1





      I have a Ticket model with hasMany relation to Approval model (multi-level approval workflow). Approval belongsTo a User.



      For a particular use case, I'll have to filter all the pending approvals to be made by a User and show him his to be approved Tickets.



      Have solved like so -



      models.Ticket.findAll({
      include: [{
      model: models.Approval,
      where: { userId: options.userId }
      }]
      }).then(function(tickets){...


      Gives me the filtered tickets but I've to also get the list of all approvals for the ticket to show the approval workflow. Can this be done by a single query in Sequelize?



      Data (T is Ticket, A is Approval and U is User) -

      T1 - A1/U1, A2/U2, A3/U3
      T2 - A4/U2
      T3 - A5/U1, A6/U4

      Output for U1 -

      T1 - A1/U1
      T3 - A5/U1

      Expected for U1 -

      T1 - A1/U1, A2/U2, A3/U3
      T3 - A5/U1, A6/U4









      share|improve this question















      I have a Ticket model with hasMany relation to Approval model (multi-level approval workflow). Approval belongsTo a User.



      For a particular use case, I'll have to filter all the pending approvals to be made by a User and show him his to be approved Tickets.



      Have solved like so -



      models.Ticket.findAll({
      include: [{
      model: models.Approval,
      where: { userId: options.userId }
      }]
      }).then(function(tickets){...


      Gives me the filtered tickets but I've to also get the list of all approvals for the ticket to show the approval workflow. Can this be done by a single query in Sequelize?



      Data (T is Ticket, A is Approval and U is User) -

      T1 - A1/U1, A2/U2, A3/U3
      T2 - A4/U2
      T3 - A5/U1, A6/U4

      Output for U1 -

      T1 - A1/U1
      T3 - A5/U1

      Expected for U1 -

      T1 - A1/U1, A2/U2, A3/U3
      T3 - A5/U1, A6/U4






      javascript node.js postgresql sequelize.js






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 23 at 21:54

























      asked Nov 22 at 10:35









      Himavanth

      11529




      11529
























          2 Answers
          2






          active

          oldest

          votes

















          up vote
          0
          down vote













          This is kind of tricky , but this way you can achieve the result in single query ,



          models.Approval.findAll({
          where: { userId: options.userId } // <---- Get all the approvals for user
          include: [{
          model: models.Ticket, // <----- Get all tickets for it
          include: [{
          model: models.Approval // <---- Get all the approvals for that ticket
          }]
          }]
          })



          NOTE : I haven't tried this one but as long as I know this should
          work.







          share|improve this answer





















          • Thanks for the reply and it works definitely. But isn't it possible in any other way to do the query on Ticket as base model?User ID here is being used as an optional filter in a bigger use case.
            – Himavanth
            Nov 22 at 17:26










          • @Himavanth , in that case you need to fetch the ticket's id first , means 2 queries , that way you can do that.
            – Vivek Doshi
            Nov 22 at 17:29


















          up vote
          0
          down vote



          accepted










          Found a workaround to solve it in one query.



          Update Ticket to have two associations on Approval with the same foreign key (one with an alias defined) -



          Ticket.hasMany(models.Approval, {
          foreignKey: 'ticketId',
          };
          Ticket.hasMany(models.Approval, {
          as: 'ApprovalFilter',
          foreignKey: 'ticketId',
          };


          Then filter using multiple includes -



          models.Ticket.findAll({
          include: [{
          model: models.Approval,
          as: 'ApprovalFilter',
          where: { userId: options.userId },
          }, {
          model: models.Approval,
          }]
          }).then(function(tickets){...





          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',
            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%2f53428989%2fsequelize-how-to-query-model-by-1n-association-but-include-all-associated-obj%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            0
            down vote













            This is kind of tricky , but this way you can achieve the result in single query ,



            models.Approval.findAll({
            where: { userId: options.userId } // <---- Get all the approvals for user
            include: [{
            model: models.Ticket, // <----- Get all tickets for it
            include: [{
            model: models.Approval // <---- Get all the approvals for that ticket
            }]
            }]
            })



            NOTE : I haven't tried this one but as long as I know this should
            work.







            share|improve this answer





















            • Thanks for the reply and it works definitely. But isn't it possible in any other way to do the query on Ticket as base model?User ID here is being used as an optional filter in a bigger use case.
              – Himavanth
              Nov 22 at 17:26










            • @Himavanth , in that case you need to fetch the ticket's id first , means 2 queries , that way you can do that.
              – Vivek Doshi
              Nov 22 at 17:29















            up vote
            0
            down vote













            This is kind of tricky , but this way you can achieve the result in single query ,



            models.Approval.findAll({
            where: { userId: options.userId } // <---- Get all the approvals for user
            include: [{
            model: models.Ticket, // <----- Get all tickets for it
            include: [{
            model: models.Approval // <---- Get all the approvals for that ticket
            }]
            }]
            })



            NOTE : I haven't tried this one but as long as I know this should
            work.







            share|improve this answer





















            • Thanks for the reply and it works definitely. But isn't it possible in any other way to do the query on Ticket as base model?User ID here is being used as an optional filter in a bigger use case.
              – Himavanth
              Nov 22 at 17:26










            • @Himavanth , in that case you need to fetch the ticket's id first , means 2 queries , that way you can do that.
              – Vivek Doshi
              Nov 22 at 17:29













            up vote
            0
            down vote










            up vote
            0
            down vote









            This is kind of tricky , but this way you can achieve the result in single query ,



            models.Approval.findAll({
            where: { userId: options.userId } // <---- Get all the approvals for user
            include: [{
            model: models.Ticket, // <----- Get all tickets for it
            include: [{
            model: models.Approval // <---- Get all the approvals for that ticket
            }]
            }]
            })



            NOTE : I haven't tried this one but as long as I know this should
            work.







            share|improve this answer












            This is kind of tricky , but this way you can achieve the result in single query ,



            models.Approval.findAll({
            where: { userId: options.userId } // <---- Get all the approvals for user
            include: [{
            model: models.Ticket, // <----- Get all tickets for it
            include: [{
            model: models.Approval // <---- Get all the approvals for that ticket
            }]
            }]
            })



            NOTE : I haven't tried this one but as long as I know this should
            work.








            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 22 at 11:21









            Vivek Doshi

            20.1k22651




            20.1k22651












            • Thanks for the reply and it works definitely. But isn't it possible in any other way to do the query on Ticket as base model?User ID here is being used as an optional filter in a bigger use case.
              – Himavanth
              Nov 22 at 17:26










            • @Himavanth , in that case you need to fetch the ticket's id first , means 2 queries , that way you can do that.
              – Vivek Doshi
              Nov 22 at 17:29


















            • Thanks for the reply and it works definitely. But isn't it possible in any other way to do the query on Ticket as base model?User ID here is being used as an optional filter in a bigger use case.
              – Himavanth
              Nov 22 at 17:26










            • @Himavanth , in that case you need to fetch the ticket's id first , means 2 queries , that way you can do that.
              – Vivek Doshi
              Nov 22 at 17:29
















            Thanks for the reply and it works definitely. But isn't it possible in any other way to do the query on Ticket as base model?User ID here is being used as an optional filter in a bigger use case.
            – Himavanth
            Nov 22 at 17:26




            Thanks for the reply and it works definitely. But isn't it possible in any other way to do the query on Ticket as base model?User ID here is being used as an optional filter in a bigger use case.
            – Himavanth
            Nov 22 at 17:26












            @Himavanth , in that case you need to fetch the ticket's id first , means 2 queries , that way you can do that.
            – Vivek Doshi
            Nov 22 at 17:29




            @Himavanth , in that case you need to fetch the ticket's id first , means 2 queries , that way you can do that.
            – Vivek Doshi
            Nov 22 at 17:29












            up vote
            0
            down vote



            accepted










            Found a workaround to solve it in one query.



            Update Ticket to have two associations on Approval with the same foreign key (one with an alias defined) -



            Ticket.hasMany(models.Approval, {
            foreignKey: 'ticketId',
            };
            Ticket.hasMany(models.Approval, {
            as: 'ApprovalFilter',
            foreignKey: 'ticketId',
            };


            Then filter using multiple includes -



            models.Ticket.findAll({
            include: [{
            model: models.Approval,
            as: 'ApprovalFilter',
            where: { userId: options.userId },
            }, {
            model: models.Approval,
            }]
            }).then(function(tickets){...





            share|improve this answer

























              up vote
              0
              down vote



              accepted










              Found a workaround to solve it in one query.



              Update Ticket to have two associations on Approval with the same foreign key (one with an alias defined) -



              Ticket.hasMany(models.Approval, {
              foreignKey: 'ticketId',
              };
              Ticket.hasMany(models.Approval, {
              as: 'ApprovalFilter',
              foreignKey: 'ticketId',
              };


              Then filter using multiple includes -



              models.Ticket.findAll({
              include: [{
              model: models.Approval,
              as: 'ApprovalFilter',
              where: { userId: options.userId },
              }, {
              model: models.Approval,
              }]
              }).then(function(tickets){...





              share|improve this answer























                up vote
                0
                down vote



                accepted







                up vote
                0
                down vote



                accepted






                Found a workaround to solve it in one query.



                Update Ticket to have two associations on Approval with the same foreign key (one with an alias defined) -



                Ticket.hasMany(models.Approval, {
                foreignKey: 'ticketId',
                };
                Ticket.hasMany(models.Approval, {
                as: 'ApprovalFilter',
                foreignKey: 'ticketId',
                };


                Then filter using multiple includes -



                models.Ticket.findAll({
                include: [{
                model: models.Approval,
                as: 'ApprovalFilter',
                where: { userId: options.userId },
                }, {
                model: models.Approval,
                }]
                }).then(function(tickets){...





                share|improve this answer












                Found a workaround to solve it in one query.



                Update Ticket to have two associations on Approval with the same foreign key (one with an alias defined) -



                Ticket.hasMany(models.Approval, {
                foreignKey: 'ticketId',
                };
                Ticket.hasMany(models.Approval, {
                as: 'ApprovalFilter',
                foreignKey: 'ticketId',
                };


                Then filter using multiple includes -



                models.Ticket.findAll({
                include: [{
                model: models.Approval,
                as: 'ApprovalFilter',
                where: { userId: options.userId },
                }, {
                model: models.Approval,
                }]
                }).then(function(tickets){...






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 23 at 21:34









                Himavanth

                11529




                11529






























                    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.





                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                    Please pay close attention to the following guidance:


                    • 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%2f53428989%2fsequelize-how-to-query-model-by-1n-association-but-include-all-associated-obj%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







                    Popular posts from this blog

                    A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks

                    Calculate evaluation metrics using cross_val_predict sklearn

                    Insert data from modal to MySQL (multiple modal on website)