Skip to content

Query with nested include and custom join condition #1869

Description

@alekbarszczewski

I am using master.
I prepared gist with 3 files: .js is actual test, .json is json output from test and .sql is SQL generated by Sequelize that makes sequelize to produce invalid result.
https://gist.github.com/alekbarszczewski/e66cbb99f95debf1e4ce

Basically what I want is:

Playlist.find({
            where: { id: 1 },
            include: [
                {
                    model: Post,
                    where: [
                        'EXISTS('+
                        'SELECT "PostTranslations2"."id" '+
                        'FROM "PostTranslations" AS "PostTranslations2"'+
                        'WHERE "PostTranslations2"."lang" = \'en-us\' AND "Posts"."id" = "PostTranslations2"."PostId"'+
                        ')'
                    ],
                    required: false,
                    include: [
                        { model: PostTranslation, where: { lang: 'en-us' }, required: false }
                    ]
                }
            ]   
        })

Unfortunately it does not work (you can see in gist) because my custom join query (EXISTS(...)) is applied to wrong JOIN table. Joins are as follows:

Playlists -> PlaylistsPosts -> *Posts* -> PostTranslations

Is it possible to apply custom join condition to PlaylistsPosts in this query?
Maybe there is other workaround?

I guess I could do something like:

Playlist.find({
   include: [{ model: PlaylistsPosts, include: [{ model: Post }] }]
})

But then I would get result in wrong format -> each playlist would have playlistsPosts and then each playlistsPost would have post attribute...

Activity

  1. mickhansen commented on Jun 6, 2014

    @mickhansen
    Contributor

    Querying on the through model/join table is not possible currently unfortuneatly.

  2. lucaswxp commented on Sep 25, 2014

    @lucaswxp

    I tried querying associations with conditions and it worked:

    User.findAll({include: [{model: Post, where: {active: true}}]
    INNER JOIN `posts` AS `post` ON `users`.`id` = `post`.`user_id` AND `post`.`active`=true

    Shouldn't this be closed?

  3. mickhansen commented on Sep 25, 2014

    @mickhansen
    Contributor

    @lucaswxp the issue is about filtering on join table models - You example is just filtering on the target model :)

  4. lvarayut commented on Jan 23, 2015

    @lvarayut

    +1 I'm having the same issue. It's would be nice to have this feature.

  5. mickhansen commented on Jan 23, 2015

    @mickhansen
    Contributor

    @lvarayut what does your code look like? It's possible to ammend the join conditions with include.where, not overwrite, do you need to overwrite?

  6. lvarayut commented on Jan 23, 2015

    @lvarayut

    @mickhansen I want to join two tables using and condition as following:

    SELECT * FROM InterviewSummaries as summary JOIN UserProfiles as profile ON 
    (summary.StudentId = profile.id AND summary.version = profile.version)
  7. mickhansen commented on Jan 23, 2015

    @mickhansen
    Contributor

    @lvarayut i see

    summary.StudentId = profile.id is already supported obviously but yes summary.version = profile.version might be an issue, but should not be too hard to implement actually.

    Perhaps an API like:

    include: [{model: UserProfile, where: {summary: {$field: UserProfile.rawAttributes.version}}]
  8. mickhansen commented on Jan 23, 2015

    @mickhansen
    Contributor

    Perhaps you could already do it like:

    include: [{model: UserProfile, where: {summary: sequelize.literal('profile.version')}}]
  9. lvarayut commented on Jan 23, 2015

    @lvarayut

    Thanks @mickhansen for your quick response. I'ill try it soon. :)

  10. eclipse1985 commented on Jul 26, 2015

    @eclipse1985

    Is querying on the through model/join table now possible with version 3.*?

  11. janmeier commented on Jul 26, 2015

    @janmeier
    Member

    @eclipse1985 Yes include: [ { model .., through: { where: .. } }]

  12. eclipse1985 commented on Jul 26, 2015

    @eclipse1985

    Oh thanks, from which version exactly?

  13. 7 remaining items

  14. cesar2064 commented on Aug 2, 2017

    @cesar2064

    I know is not the best solution, but I have solved a similar issue with this implementation:

        models.PartnerProspectModel.findAll({
                    where: {
                        status: 0
                    },
                    include: [{
                            model: models.UserModel,
                            as: 'prospect_user',
                            duplicating: false,
                            required: true,
                            where: {
                                role: 2
                            },
                            include: [
                                {
                                    model: models.UserVideoModel,
                                    as: 'user_videos',
                                    duplicating: false,
                                    required: true,
                                    include: [
                                        {
                                            model: models.VideoModel,
                                            as: 'video',
                                            where: models._sequelize.literal('NOT (((`prospect_user->user_videos->video`.`total_video_time` * 100) / `prospect_user->user_videos`.`current_time`) < 90)'),
                                            duplicating: false,
                                            required: true
                                        }
                                    ]
                                }
                            ]
                        },  ...(more code)
    

    This is with sequelize 4.4.2, I don't know if it is working in previous versions.

  15. cybercarnage commented on Sep 15, 2017

    @cybercarnage

    @janmeier Thanks. 'through' and 'required: true' helped me.
    My Example:
    I need 'Sites' only with 'Craft' association, where 'Craft' entry exists and (Site.planExpiredDate > current date).

    associate:
    SiteCategoryName.belongsToMany(models.Site, {as: 'Sites', through: 'SiteCategory', foreignKey: 'categoryId'});

    Site.hasOne(models.CraftSite, { as: 'Craft', foreignKey: 'siteId' });

    This worked for me
    models.SiteCategoryName.findAll({ through: { where: { planExpiredDate: { $gt: new Date() } } }, include: [ { model: models.Site, as: 'Sites', include: [ { model: models.CraftSite, as: 'Craft', required: true } ] } ], limit: process.env.ADMIN_PER_PAGE // 10 })

  16. jeremybradbury commented on Jan 11, 2018

    @jeremybradbury

    why doesn't this work?

    let options = {where: { table: { field: "value" }, anotherTable: {anotherField: "anotherValue"}, include: [anotherTable] };
    

    and instead of all kinds of messy nested JS code to make mess SQL code... 1 JOIN, 2 WHEREs no subqueries easily stacked with AND by default like other native queries

    SELECT *
    FROM table JOIN anotherTable ON table.fkid = anotherTable.pkid
    WHERE table.field = "value" AND anotherTable.anotherField = "anotherValue" ;
    

    ...this lib constantly makes me do all kinds of extra loops and object manipulation, strange native static methods AND/OR raw queries.

  17. cesar2064 commented on Jan 11, 2018

    @cesar2064

    nice suggestion, @jeremybradbury, if you dont like it you are free to use a different one or create your own lib..

  18. jeremybradbury commented on Jan 12, 2018

    @jeremybradbury

    @cesar2064 I know i bitch a lot but I really do appreciate this lib. I was actually in the midst of doing exactly what you suggested before finding Sequelize and moving to it in a time crunch. but right now reporting is all done in raw queries and filtering is becoming mind-numbing.

    I am in the middle of building function to format queries like the above into something to filter related tables with. I'll come back with something useful in the next day or so even it uses raws.

  19. jeremybradbury commented on Jan 12, 2018

    @jeremybradbury

    i ended up building a raw filter query of just ids... dynamically adding joins and where sections depending on the object passed in into an array of ids then passed it into the original query like this:

    list => {
      let q = [];
      for(i in list) {
        q.push(list[i].id);
      }
      return Model.findAll({where: {id: q}, include: [<fun list of relations>]})
    

    where list is the raw query result

    now my brain hurts

  20. bharatkapse commented on Aug 8, 2018

    @bharatkapse

    I have four tables join by belongsTo relationship. location belongs to city, city belongs to state and state belongs to country. when i search for a location by id and wish to get city, state and country in the response then I include these model in nested include format like the following.

    router.get('/getLocation/:id',function(req,res){
    location.findOne({
    where:{id:req.params.id},
    include:[{
    model:city,
    attributes:['name'],
    include:[{
    model:state,
    attributes:['name'],
    include:[{
    model:country,
    attributes:['name']
    }]
    }]
    }]
    }).then(function(Location){
    res.json(Location);
    });
    });

    And the response I am getting is like the following

    {
    "id": "1",
    "displayname": "VimanNagar",
    "name": "VimanNagar",
    "city_id": "3",
    "city": {
    "name": "Pune",
    "state": {
    "name": "Maharashtra",
    "country": {
    "name": "India"
    }
    }
    }
    }

    How can I get the response as following

    {
    "id": "1",
    "displayname": "VimanNagar",
    "name": "VimanNagar",
    "city":"Pune",
    "state":"Maharashtra",
    "country":"India"
    }
    please help me out here

  21. BolajiOlajide commented on Dec 28, 2018

    @BolajiOlajide

    @jacinto123 Were you able to get a fix?

  22. BolajiOlajide commented on Dec 28, 2018

    @BolajiOlajide

    I was able to get around this by using this query instead

          const clause2 = 'failed';
          const currentDate = new Date();
    
          const defaultingLoans = await Loan.findAll({
            offset,
            limit,
            where: {
              [Op.and]: database.sequelize.literal(`EXISTS(SELECT * FROM "Instalments" WHERE "Instalments"."loanId" = "Loan"."id" AND "Instalments"."dueDate" < '${currentDate}' AND "Instalments"."status" IN ('${clause1}', '${clause2}'))`)
            },
            include: [Instalment, 'Owner', 'Approver']
          });```
    
  23. niyasshefeek commented on May 6, 2019

    @niyasshefeek

    what to do with this case ?
    3 table Join and One table has value Json Type and joining other table using the JSON value.

    ` SELECT a.idListing,a.listingtitle,a.listingImage,c.name

    FROM listing a LEFT JOIN listingcategory b ON a.listingCategory = b.idListingCategory

    LEFT JOIN offercateogry c ON JSON_CONTAINS(a.offercategory, CAST(c.idofferCateogry as JSON), '$'); `

  24. idmega2000 commented on Apr 11, 2020

    @idmega2000

    I had the same issue and I was able to fix it with.

    
    const getWorkflowByActions = await Workflow.findAndCountAll({
      where: {
          [Op.and]: [
            Sequelize.literal(`EXISTS (select workflowId from Actions where
            "workflowId" = "workflow".id AND status=:myStatus AND actor=:actorId)`),
          ]
      },
      order: [['updatedAt', 'DESC']],
      limit,
      offset,
      include: [
      {
        model: Action,
        as: 'actionTaker',
      }],
      replacements: {
        myStatus,
        actorId,
      },
    });
    

    What I did here is to run a subquery that get all the workflow id that meets the necessary conditions in the Action table(It's a one to many table).If the condition is met in one of the many data, I select the Id and then use the main query to generate the necessary data base on those workflowid selected from the Actions table.

  25. added theissue type on Mar 9, 2025
  26. removed
    type: feature
    on Mar 9, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions