Skip to content

Erroneous query when including hasMany and hasOne relations with a limit #4798

Closed

Description

@svvac

When using a model similar to this:

var Parent  = sequelize.define('Parent',  { field: Sequelize.STRING });
var Child   = sequelize.define('Child',   { field: Sequelize.STRING });
var Partner = sequelize.define('Partner', { field: Sequelize.STRING });

Parent.hasMany(Child);
Parent.hasOne(Partner);

Attempting to retrieve values by filtering on Partner fields results in an ER_BAD_FIELD_ERROR: Unknown column 'Partner.field' in 'where clause':

Parent.findAll({
    include: [ Partner, Child ],
    where: {
        '$Partner.field$': 'bbb',
    },
    limit: 1,
});

This is because Sequelize performs the lookup on the main model (Parent) in a sub-query in order for the limit to apply on the number of persons being returned. However, the condition is applied on the subquery, without the proper JOIN clause:

SELECT `Parent`.*,
    `Partner`.`id` AS `Partner.id`,
    `Partner`.`field` AS `Partner.field`,
    `Partner`.`createdAt` AS `Partner.createdAt`,
    `Partner`.`updatedAt` AS `Partner.updatedAt`,
    `Partner`.`ParentId` AS `Partner.ParentId`,
    `Children`.`id` AS `Children.id`,
    `Children`.`field` AS `Children.field`,
    `Children`.`createdAt` AS `Children.createdAt`,
    `Children`.`updatedAt` AS `Children.updatedAt`,
    `Children`.`ParentId` AS `Children.ParentId`
FROM (
    SELECT `Parent`.`id`,
        `Parent`.`field`,
        `Parent`.`createdAt`,
        `Parent`.`updatedAt`
    FROM `Parents` AS `Parent`
    WHERE `Partner`.`field` = 'bbb' LIMIT 1
    ) AS `Parent`
LEFT JOIN `Partners` AS `Partner`
    ON `Parent`.`id` = `Partner`.`ParentId`
LEFT JOIN `Children` AS `Children`
    ON `Parent`.`id` = `Children`.`ParentId`;

Sequelize should JOIN the models with a 1 cardinality to the main model in the subquery in order for the WHERE conditions to behave as expected. Models with higher caardinality thus won't be filterable this way, but it is expected as it should probably be handled in a WHERE clause specified in the appropriate include.

Full example below:

'use strict';

var Sequelize = require('sequelize');
var Promise = Sequelize.Promise;

var sequelize = new Sequelize('test', 'root', '', { logging: console.log });

var Parent  = sequelize.define('Parent',  { field: Sequelize.STRING });
var Child   = sequelize.define('Child',   { field: Sequelize.STRING });
var Partner = sequelize.define('Partner', { field: Sequelize.STRING });

Parent.hasMany(Child);
Parent.hasOne(Partner);

sequelize.sync({ force: true })

    // Create objects
    .then(function () {
        return Promise.props({
            childs: Promise.all([
                Child.create({ field: 'aaa' }),
                Child.create({ field: 'bbb' }),
                Child.create({ field: 'ccc' }),
            ]),
            partners: Promise.all([
                Partner.create({ field: 'aaa' }),
                Partner.create({ field: 'bbb' }),
                Partner.create({ field: 'ccc' }),
            ]),
            parents: Promise.all([
                Parent.create({ field: 'aaa' }),
                Parent.create({ field: 'bbb' }),
                Parent.create({ field: 'ccc' }),
            ]),
        });
    })

    .bind({})

    // Create relations in order to have some data
    .then(function (objects) {
        this.objects = objects;

        this.objects.parents[0].setChildren([
            this.objects.childs[0],
            this.objects.childs[2],
        ]);

        this.objects.parents[1].setChildren([
            this.objects.childs[1],
        ]);

        this.objects.parents[0].setPartner(this.objects.partners[2]);
        this.objects.parents[2].setPartner(this.objects.partners[1]);

        return Promise.all([
            this.objects.parents[0].save(),
            this.objects.parents[1].save(),
            this.objects.parents[2].save(),
            this.objects.partners[0].save(),
            this.objects.partners[1].save(),
            this.objects.partners[2].save(),
            this.objects.childs[0].save(),
            this.objects.childs[1].save(),
            this.objects.childs[2].save(),
        ]);
    })
    .all()
    .delay(1000)

    .then(function () {
        return Parent.findAll({
            include: [ Partner, Child ],
            where: {
                '$Partner.field$': 'bbb',
            },

            limit: 1,
        });
    })


    .then(function (matches) {
        console.log(matches);
    })

;

Activity

  1. mickhansen commented on Nov 3, 2015

    @mickhansen
    Contributor

    Why are you using the $table.field$ in this example?
    The regular include.where should solve this case.

  2. svvac commented on Nov 3, 2015

    @svvac
    Author

    Well, this is a minimal example demonstrating the issue. In my use case, I'm building dynamic filters specified by the user and it is much more practical to use the alternate approach (i.e. $<field>$) than dynamically resolve the right where in the include tree.

    It also allows doing more complex queries such as the one below that are otherwise impossible.

    {
        // ...
        where: {
            $or: [
                { '$AModel.field$': value },
                { '$AnotherModel.field$': value },
            ]
        }
    }
  3. mickhansen commented on Nov 3, 2015

    @mickhansen
    Contributor

    Won't be trivial to fix. There's no logic for $$ and we don't expect to implement any.
    In this specific case you need left joins on the inner query on subqueries that add the filter and do a limit 1.
    No idea how to express that generically.

  4. svvac commented on Nov 3, 2015

    @svvac
    Author

    Well, basically to write the query in the stead of Sequelize, right ?

  5. mickhansen commented on Nov 3, 2015

    @mickhansen
    Contributor

    Thats the quick workaround yes :)

  6. svvac commented on Nov 4, 2015

    @svvac
    Author

    Alright, thanks for the insight. What would be the best way to stay tuned to changes relating to this issue? Do you intend to post them here? I'm asking since you seem to have quite a lot of them to handle and I doubt you can keep track of all of them :)

  7. mickhansen commented on Nov 4, 2015

    @mickhansen
    Contributor

    Good question, no idea how to start handling this issue.
    But generally when we fix/implement something we cut a new release where we reference issue and pull requests (or we try to).
    And then we ofcourse close relevant issues aswell.

  8. svvac commented on Sep 1, 2017

    @svvac
    Author

    AFAIK, this has not been fixed yet.

  9. miladmeidanshahi commented on May 5, 2020

    @miladmeidanshahi

    same problem

  10. hussammaher commented on Nov 30, 2021

    @hussammaher

    any idea how to solve this problem ??

  11. rodolfo-valtierra commented on Mar 3, 2022

    @rodolfo-valtierra

    I just resolved one

    • one of the problems is that how do you relate in sequelize for example: maybe you have hasMany when you should have hasOne check the includes one by one and you reallize what is the relation that you have to change
    • also add subQuery: true
      include: {
      association: 'city'
      },
      subQuery: true
  12. ephys commented on Mar 4, 2022

    @ephys
    Member

    Let's continue this conversation in #12971 :) (I know it's newer than this thread but I was made aware of it earlier than this one)

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

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions