Skip to content

Querying on where association #3095

Closed
Closed

Description

@toaster33

Curious if the implementation has changed on how to query on associations. I created a test case that used to work on v2.0.0-rc8 but is currently not working on v2.0.0. Was hoping for some clarity on how to adjust my code for the new changes. Thanks for assistance.

Test case link

v2.0.0-rc8 query:

    `Company`.`id`,
    `Company`.`name`,
    `Company`.`createdAt`,
    `Company`.`updatedAt`,
    `Company`.`presidentId`,
    `Company`.`departmentId`,
    `President`.`id` AS `President.id`,
    `President`.`name` AS `President.name`,
    `President`.`createdAt` AS `President.createdAt`,
    `President`.`updatedAt` AS `President.updatedAt`,
    `Department`.`id` AS `Department.id`,
    `Department`.`name` AS `Department.name`,
    `Department`.`createdAt` AS `Department.createdAt`,
    `Department`.`updatedAt` AS `Department.updatedAt`,
    `Department`.`leadId` AS `Department.leadId`,
    `Department.Lead`.`id` AS `Department.Lead.id`,
    `Department.Lead`.`name` AS `Department.Lead.name`,
    `Department.Lead`.`createdAt` AS `Department.Lead.createdAt`,
    `Department.Lead`.`updatedAt` AS `Department.Lead.updatedAt`
FROM
    `Companies` AS `Company`
        LEFT OUTER JOIN
    `Users` AS `President` ON `Company`.`presidentId` = `President`.`id`
        LEFT OUTER JOIN
    `Departments` AS `Department` ON `Company`.`departmentId` = `Department`.`id`
        LEFT OUTER JOIN
    `Users` AS `Department.Lead` ON `Department`.`leadId` = `Department.Lead`.`id`
WHERE
    (`President`.`name` = 'OurLead'
        OR `Department.Lead`.`name` = 'OurLead');

v2.0.0 query:

    `Company`.`id`,
    `Company`.`name`,
    `Company`.`createdAt`,
    `Company`.`updatedAt`,
    `Company`.`presidentId`,
    `Company`.`departmentId`,
    `President`.`id` AS `President.id`,
    `President`.`name` AS `President.name`,
    `President`.`createdAt` AS `President.createdAt`,
    `President`.`updatedAt` AS `President.updatedAt`,
    `Department`.`id` AS `Department.id`,
    `Department`.`name` AS `Department.name`,
    `Department`.`createdAt` AS `Department.createdAt`,
    `Department`.`updatedAt` AS `Department.updatedAt`,
    `Department`.`leadId` AS `Department.leadId`,
    `Department.Lead`.`id` AS `Department.Lead.id`,
    `Department.Lead`.`name` AS `Department.Lead.name`,
    `Department.Lead`.`createdAt` AS `Department.Lead.createdAt`,
    `Department.Lead`.`updatedAt` AS `Department.Lead.updatedAt`
FROM
    `Companies` AS `Company`
        LEFT OUTER JOIN
    `Users` AS `President` ON `Company`.`presidentId` = `President`.`id`
        LEFT OUTER JOIN
    `Departments` AS `Department` ON `Company`.`departmentId` = `Department`.`id`
        LEFT OUTER JOIN
    `Users` AS `Department.Lead` ON `Department`.`leadId` = `Department.Lead`.`id`
WHERE
    (`Company`.`President.name` = 'OurLead'
        OR `Company`.`Department.Lead.name` = 'OurLead');

Activity

  1. mickhansen commented on Feb 10, 2015

    @mickhansen
    Contributor

    Pretty sure that where with nested keys didn't work in rc8 either.
    But yeah nested keys are insanely error prone so we don't really support them currently.

  2. mickhansen commented on Feb 10, 2015

    @mickhansen
    Contributor

    We need some new syntax for defining include based where's that don't go on a join (for OR) mostly.

  3. DavidTPate commented on Feb 11, 2015

    @DavidTPate
    Contributor

    I don't think it is the right long term solution, but I think this could be accomplished in the short term (until a better solution is implemented) using a literal. If you know the table name, as we do in that test case I think we could just do:

    where: Sequelize.or({Sequelize.literal('`President`.`name`'): 'OurLead'}, {Sequelize.liternal('`Department.Lead`.`name`'): 'OurLead'})

    instead of

    where: Sequelize.or({'President.name': 'OurLead'}, {'Department.Lead.name': 'OurLead'})
  4. mickhansen commented on Feb 11, 2015

    @mickhansen
    Contributor

    @DavidTPate Unfortuneatly literal() can't be used as a key.
    I'm very open to general API discussion for this. But i don't think relying on nested keys is the way to go.

  5. toaster33 commented on Feb 12, 2015

    @toaster33
    Author

    I think I was able to narrow down the cause...

    \abstract\query-generator.js
    v2.0.0

    else if (Utils._.isPlainObject(smth)) {
            return self.whereItemsQuery(smth, {
              model: factory,
              prefix: prepend && tableName
            });
          }
    

    v2.0.0-rc8

    else if (Utils._.isPlainObject(smth)) {
            if (prepend) {
              if (tableName) options.keysEscaped = true;
              smth = this.prependTableNameToHash(tableName, smth);
            }
            result = this.hashToWhereConditions(smth, factory, options);
          }
    
  6. toaster33 commented on Feb 13, 2015

    @toaster33
    Author

    To get conversations / ideas rolling...

    First I was thinking another attribute within the include but cannot figure out how the attribute would be combined with other attributes. If the following existed, I still would not know if the attributes should be ANDed or ORed.

    {
      include: [
        {
          model: President,
          attribute: Sequelize.and({name: 'OurLead'})
        },
        {
          model: Department,
          attribute: Sequelize.and({name: 'OurLead'})
        }
      ]
    }
    

    Building out the where using includes but this seems too cumbersome and redundant:

    {
      where: Sequelize.or({
        include: [
          model: 'Users',
          as: 'President',
          where: { name: 'OurLead' }
        ]
      },
      {
        include: [
          model: Departments,
          as: Department,
          include: [
            model: 'Users',
            as: 'Department.Lead',
            where: { name: 'OurLead' }
          ]
        ]
      })
    }
    

    Another variation of what worked previously (please refer to test link line 80):

    {
      where: Sequelize.or(
        { Company.associations.President.as: { name: 'OurLead' }},
        { Section.associations.Lead.as: { name: 'OurLead' }},
      )
    }
    
  7. mickhansen commented on Feb 13, 2015

    @mickhansen
    Contributor

    Unfortuneatly it's not possible to have references as keys (atleast in ES5).
    The problem with nested keys is that it was error prone, but perhaps we could use a special syntax to denote that it's an include: {'$Company.Department.key$': value}.
    That still poses a general issue though, we took out include on string because it was very error prone and not very deterministic.

  8. mickhansen commented on Feb 13, 2015

    @mickhansen
    Contributor

    Since it's possible to save association references, perhaps something like:

    where: {
      $or: [
        {$association: Company.associations.President, where: {
          name: 'OurLead'
        }}
      ]
    }
  9. toaster33 commented on Feb 14, 2015

    @toaster33
    Author

    I like your last suggestion which would not incur much of a change (at least for me).

  10. added
    type: feature
    P1: important
    on Feb 15, 2015
  11. self-assigned this
    on Feb 15, 2015
  12. sebay00 commented on Feb 25, 2015

    @sebay00

    Hi there,

    Just want to know if you decided how to fix this issue / improvement ?

  13. mickhansen commented on Feb 25, 2015

    @mickhansen
    Contributor

    @sebay00 not finally, but likely the last proposal i commenetd.

  14. DavidTPate commented on Feb 25, 2015

    @DavidTPate
    Contributor

    @mickhansen I think you last suggestion of adding $association would work well.

  15. 36 remaining items

  16. ConAntonakos commented on Jun 21, 2017

    @ConAntonakos

    This issue thread really helped me find out how to use the query association syntax in the where clause from #3095 (comment): $table_name.field_name$: field_value

    I didn't see this in the docs. Is it there and I just missed it, or do we need a PR? 😄

    Edit: I see it now, but it was not easily understood at first.

    screen shot 2017-06-21 at 5 48 24 pm

  17. DavidTPate commented on Jun 22, 2017

    @DavidTPate
    Contributor

    @ConAntonakos if you don't see it in the docs, I'd suggest putting in a PR.

  18. webdeveloper0429 commented on Dec 1, 2017

    @webdeveloper0429

    here is my issue.
    when include is duplicated, error shows

    	queryParams.include = [
    		{
    			model: models.role,
    			as: 'role',
    			include: [
    				{model: models.right, as: 'rightList'}
    			]
    		}
    	]
        if (query['search'])
            queryParams.where = {
    			"$or": [
    				{
    					email: {
    						$like: '%' + query['search'] + '%'
    					}
    				},{
    					"$role.label$": {
    						$like: '%' + query['search'] + '%'
    					}
    				}
    			]
    		};
    

    if I didn't include rightList, then this query works well.
    but if I use sub include, error shows "SequelizeDatabaseError"

  19. aprilmintacpineda commented on Feb 23, 2018

    @aprilmintacpineda

    if you want to query base on the association, do it like this.

    sequelize@^4.33.4

    testfile.js

    import model from './models';
    import Sequelize, { Op } from 'sequelize';
    
    model.Service.findAll({
      where: {
        [Op.or]: {
          name: {
            [Op.like]: '%elvis%'
          },
          description: {
            [Op.like]: '%elvis%'
          },
          first_name: Sequelize.where(Sequelize.col('User.first_name'), {
            [Op.like]: '%elvis%'
          }),
          middle_name: Sequelize.where(Sequelize.col('User.middle_name'), {
            [Op.like]: '%elvis%'
          }),
          surname: Sequelize.where(Sequelize.col('User.surname'), {
            [Op.like]: '%elvis%'
          })
        }
      },
      include: [
        {
          model: model.User
        }
      ]
    })
    .then(data => {
      console.log('');
      data.forEach(d => {
        console.log('service:', d.name, 'owned by:', d.User.first_name);
      });
    });

    query generated

    SELECT
      `Service`.`service_id`,
      `Service`.`user_id`,
      `Service`.`cover_image`,
      `Service`.`name`,
      `Service`.`description`,
      `Service`.`created_at`,
      `Service`.`updated_at`,
      `Service`.`service_type_id`,
      `User`.`user_id` AS `User.user_id`,
      `User`.`first_name` AS `User.first_name`,
      `User`.`middle_name` AS `User.middle_name`,
      `User`.`surname` AS `User.surname`,
      `User`.`email` AS `User.email`,
      `User`.`password` AS `User.password`,
      `User`.`sex` AS `User.sex`,
      `User`.`profile_image` AS `User.profile_image`,
      `User`.`confirm_token` AS `User.confirm_token`,
      `User`.`is_confirmed` AS `User.is_confirmed`,
      `User`.`remember_token` AS `User.remember_token`,
      `User`.`created_at` AS `User.created_at`,
      `User`.`updated_at` AS `User.updated_at`
    FROM `service` AS `Service` LEFT OUTER JOIN `user` AS `User` ON `Service`.`user_id` = `User`.`user_id`
    WHERE (`Service`.`name` LIKE '%elvis%' OR `Service`.`description` LIKE '%elvis%' OR `User`.`first_name` LIKE '%elvis%' OR `User`.`middle_name` LIKE '%elvis%' OR `User`.`surname` LIKE '%elvis%');

    output

    service: Satterfield - Kiehn owned by: Elvis
    service: Effertz - Mitchell owned by: Elvis
    
  20. mdemblani commented on Jan 13, 2019

    @mdemblani
    Contributor

    if you want to query base on the association, do it like this.

    sequelize@^4.33.4

    testfile.js

    import model from './models';
    import Sequelize, { Op } from 'sequelize';
    
    model.Service.findAll({
      where: {
        [Op.or]: {
          name: {
            [Op.like]: '%elvis%'
          },
          description: {
            [Op.like]: '%elvis%'
          },
          first_name: Sequelize.where(Sequelize.col('User.first_name'), {
            [Op.like]: '%elvis%'
          }),
          middle_name: Sequelize.where(Sequelize.col('User.middle_name'), {
            [Op.like]: '%elvis%'
          }),
          surname: Sequelize.where(Sequelize.col('User.surname'), {
            [Op.like]: '%elvis%'
          })
        }
      },
      include: [
        {
          model: model.User
        }
      ]
    })
    .then(data => {
      console.log('');
      data.forEach(d => {
        console.log('service:', d.name, 'owned by:', d.User.first_name);
      });
    });

    query generated

    SELECT
      `Service`.`service_id`,
      `Service`.`user_id`,
      `Service`.`cover_image`,
      `Service`.`name`,
      `Service`.`description`,
      `Service`.`created_at`,
      `Service`.`updated_at`,
      `Service`.`service_type_id`,
      `User`.`user_id` AS `User.user_id`,
      `User`.`first_name` AS `User.first_name`,
      `User`.`middle_name` AS `User.middle_name`,
      `User`.`surname` AS `User.surname`,
      `User`.`email` AS `User.email`,
      `User`.`password` AS `User.password`,
      `User`.`sex` AS `User.sex`,
      `User`.`profile_image` AS `User.profile_image`,
      `User`.`confirm_token` AS `User.confirm_token`,
      `User`.`is_confirmed` AS `User.is_confirmed`,
      `User`.`remember_token` AS `User.remember_token`,
      `User`.`created_at` AS `User.created_at`,
      `User`.`updated_at` AS `User.updated_at`
    FROM `service` AS `Service` LEFT OUTER JOIN `user` AS `User` ON `Service`.`user_id` = `User`.`user_id`
    WHERE (`Service`.`name` LIKE '%elvis%' OR `Service`.`description` LIKE '%elvis%' OR `User`.`first_name` LIKE '%elvis%' OR `User`.`middle_name` LIKE '%elvis%' OR `User`.`surname` LIKE '%elvis%');

    output

    service: Satterfield - Kiehn owned by: Elvis
    service: Effertz - Mitchell owned by: Elvis
    

    This method works as long as there is a single mode in the join. It fails the moment when there is another model with a different type of relation, i.e. belongsToMany

  21. smk-data commented on Apr 21, 2019

    @smk-data

    Table0->Table1->Table2
    field_name: Sequelize.where(Sequelize.col('Table1->Table2.field_name'), {
    [Op.like]: '%field_name'%'
    }),

  22. AshBringer4eg commented on Feb 10, 2020

    @AshBringer4eg

    sry, I'm suffering the same problem, I have many different relation types inside a model, this method faileds, did you find any solution?

    You can use something like this:

    model.Service.findAll({
      where: {
        [Op.or]: {
          name: {
            [Op.like]: '%elvis%'
          },
          description: {
            [Op.like]: '%elvis%'
          }
        }
      },
      include: [
        {
          model: model.User,
          where: {
    	   [Op.or]: {
    		  first_name: {
    			[Op.like]: '%elvis%'
    		  }),
    		  middle_name: {
    			[Op.like]: '%elvis%'
    		  }),
    		  surname: {
    			[Op.like]: '%elvis%'
    		  })
    	   }
          },
    	  include: [{
    		  model: model.Data,
    		  where: {
    			first_name: {
    			  [Op.like]: '%elvis%'
    			})
    		  }
    	  }]
    	}
      ]
    })
    
  23. AshBringer4eg commented on Feb 11, 2020

    @AshBringer4eg

    this may not work in my case:
    try to use subQuery: false in findAndCountAll options. In this option your WHEREcase will be in the end of all statements.

    Project.findAndCountAll({
      where: {
        {[Op.or]: [ { name: 'testProject' }, { '$task.name$': 'testTask' } ]}
      },
      include: [
        { model: Task, required: false, include: [{ model: User, as: 'members' }] }
      ],
      subQuery: false
    })
    

    Or another solution. it may replace Task where case in one row with JOIN

    Project.findAndCountAll({
      where: {
        name: 'testProject' 
      },
      include: [{ 
          model: Task, 
          required: false, 
          where: {
            name: 'testTask'
          },
          include: [{ model: User, as: 'members' }] 
      }]
    })
    
  24. fabioespinosa commented on Mar 5, 2020

    @fabioespinosa
    Contributor

    Is it possible to reference a table querying JSONB and the $col$ operator? like:

      "$Media$.audio.length": {
        [Op.gt]: 20
      }
    }
    

    Gives me an error.

  25. vinrsr commented on Dec 17, 2020

    @vinrsr

    Does anyone realized that i found something that is working for this kind of problem. I've been suffering for 3 days and finally i found it out.

    const findInvoice = await model.invoices_ht.findAll({
            where: {
                location_id: location_id,
                status: 1,
                created_at: Op.where(Op.literal('invoices_ht.created_at '), '>', moment('2020-10-31').toDate()),
                [Op.where]: Op.literal('product_category IN (1,5,3)')
            },
            attributes: [
                'id',
                'currency',
                'amount_due',
                'date_paid',
                'recurring',
            ],
            include: [{
                model: model.invoices_dt,
                attributes: ['product_name'],
                include: [{
                    required: false, 
                    model: model.products,
                    attributes: ['product_category']
                }]
            }],
            order: [
                ['created_at', 'DESC']
            ]
        });
    
  26. AshBringer4eg commented on Dec 24, 2020

    @AshBringer4eg

    Does anyone realized that i found something that is working for this kind of problem. I've been suffering for 3 days and finally i found it out.

    Try something like this:

    const findInvoice = await model.invoices_ht.findAll({
      where: {
        location_id: location_id,
        status: 1,
        created_at: { 
          [Op.gt]: moment('2020-10-31').toDate() 
        }
      },
      attributes: ['id', 'currency', 'amount_due', 'date_paid', 'recurring'],
      include: [{
        model: model.invoices_dt,
        attributes: ['product_name'],
        include: [{
          required: false,
          model: model.products,
          attributes: ['product_category']
          where: {
            product_category: {
              [Op.in]: [1, 3, 5]
            }
          }
        }]
      }],
      order: [
        ['created_at', 'DESC']
      ]
    });
    
  27. vosho commented on Mar 9, 2021

    @vosho

    this may not work in my case:
    try to use subQuery: false in findAndCountAll options. In this option your WHEREcase will be in the end of all statements.

    Project.findAndCountAll({
      where: {
        {[Op.or]: [ { name: 'testProject' }, { '$task.name$': 'testTask' } ]}
      },
      include: [
        { model: Task, required: false, include: [{ model: User, as: 'members' }] }
      ],
      subQuery: false
    })
    

    Or another solution. it may replace Task where case in one row with JOIN

    Project.findAndCountAll({
      where: {
        name: 'testProject' 
      },
      include: [{ 
          model: Task, 
          required: false, 
          where: {
            name: 'testTask'
          },
          include: [{ model: User, as: 'members' }] 
      }]
    })
    

    The first solution has one problem:
    When in findcountall, the returned rows are not as expected when limit is used.

    The second solution is different from the original question
    The condition is or, but your reply becomes and between query and sub queries

  28. geeofree commented on Feb 25, 2022

    @geeofree

    #3095 (comment)

    Thank you! This worked for my situation. Can't believe this isn't documented however.

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

    P1: importanttype: feature

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions