Skip to content

No such column when using $model.field$ in where clause #14936

Open

Description

@kaiserfro

Issue Creation Checklist

  • I understand that my issue will be automatically closed if I don't fill in the requested information
  • I have read the contribution guidelines

Bug Description

When attempting to execute a findAll() query through multiple tables, the SQL builder creates incorrect SQL for the WHERE clause.

For the example below, the SQL statement generated is:

SELECT `Component`.`id`, `Component`.`coreLruId`, `Component`.`name`, `Component`.`createdAt`, `Component`.`updatedAt`, `coreLru`.`id` AS `coreLru.id`, `coreLru`.`core_lru_type_name` AS `coreLru.name`, `coreLru`.`createdAt` AS `coreLru.createdAt`, `coreLru`.`updatedAt` AS `coreLru.updatedAt` FROM `Components` AS `Component` LEFT OUTER JOIN `CoreLruTypes` AS `coreLru` ON `Component`.`coreLruId` = `coreLru`.`id` WHERE `coreLru`.`name` = 'Core LRU';

As you can see, the WHERE clause has a mixture of the table alias used in the the statement, but the sequelize field alias for the field name instead of the actual field name in the table. The proper output should be

`coreLru`.`core_lru_type_name`

Reproducible Example

const { Sequelize, Model, DataTypes } = require('sequelize');
const sequelize = new Sequelize('sqlite::memory:');

class Component extends Model {
  static init(sequelize, types) {
    return super.init({
      id: {
        type: types.INTEGER,
        primaryKey: true,
        autoincrement: true,
      },
      coreLruId: {
        type: types.INTEGER,
      },
      name: {
        type: types.STRING,
      }
    },
    {
      sequelize,
    })
  }

  static associate(models) {
    Component.belongsTo(CoreLruType, {
      foreignKey: 'coreLruId',
      as: 'coreLru',
    })
  }
}

class CoreLruType extends Model {
  static init(sequelize, types) {
    return super.init({
      id: {
        type: types.INTEGER,
        primaryKey: true,
        autoIncrement: true,
      },
      name: {
        type: types.STRING,
        field: 'core_lru_type_name'
      }
    },
    {
      sequelize
    })
  }
}

(async () => {
  CoreLruType.init(sequelize, Sequelize);
  Component.init(sequelize, Sequelize);
  Component.associate();

  await sequelize.sync();

  await CoreLruType.create({
    name: 'Core LRU',
  });
  const coreLru1 = await CoreLruType.findOne({ where: { name: 'Core LRU' } })
  console.log(coreLru1.get({plain: true}));
  await Component.create({
    name: 'Component1',
    coreLruId: coreLru1.id,
  });
  const component1 = await Component.findOne({ where: { name: 'Component1' }})
  console.log(component1.get({plain: true}));

  const result = await Component.findAll({
    where: {
      '$coreLru.name$': 'Core LRU',
    },
    include: [
      {
        model: CoreLruType,
        as: 'coreLru',
        include: [],
      }
    ]
  })
  console.log(result);
})();

What do you expect to happen?

The proper output for the WHERE clause should be

`coreLru`.`core_lru_type_name`

What is actually happening?

What it looks like is the where portion of the findAll() call is not converting between sequelize field names and SQL field names. The coreLru portion, although it matches the relationship name in the model, its probably actually referring to the include.as entry...which would imply that the field name portion would need to match the SQL field name, not the model field name. Note that if this was changed to $coreLru.core_lru_type_name$, the problem would go away.

It appears that the field name aliases used in the model only affect the SELECT clause, and not the WHERE clause, when using this complex where clause form.

The examples in the documentation regarding Complex where clauses at the top level only show situations where the database field name and the sequelize field name match each other. It is unclear, when they do not match, what the where clause should look like.

I'd like to get clarification on whether this behavior is intentional or not. This behavior feels incorrect, considering that if you query a table directly, you would not use table field names in the query...or if you move the where clause into the include portion, you would not use the table field names.

Lastly, the question will come up, "why don't you move the where clause at the top into the include section instead?". Although that would work for this simple situation, it does not work for the more complex situation I'm writing this bug for. In that situation, I have 3 fields from different related tables that need to be ORed together. Moving these into the include section doesn't create the appropriate SQL.

Environment

  • Sequelize version: 6.21.4
  • Node.js version: v18.7.0
  • If TypeScript related: TypeScript version:
  • Database & Version: Sqlite
  • Connector library & Version:[email protected]

Would you be willing to resolve this issue by submitting a Pull Request?

  • Yes, I have the time and I know how to start.
  • Yes, I have the time but I will need guidance.
  • No, I don't have the time, but my company or I are supporting Sequelize through donations on OpenCollective.
  • No, I don't have the time, and I understand that I will need to wait until someone from the community or maintainers is interested in resolving my issue.

Indicate your interest in the resolution of this issue by adding the 👍 reaction. Comments such as "+1" will be removed.

Activity

  1. github-actions commented on Sep 10, 2022

    @github-actions
  2. added
    type: bug
    and removed on Sep 17, 2022
  3. eruhaji commented on Oct 1, 2022

    @eruhaji

    @evanrittenhouse I'd like to work on this issue, can you assign it to me?

  4. fzn0x commented on Oct 1, 2022

    @fzn0x
    Member

    Assigned, PR welcome :)

  5. 4ndrzej commented on Feb 1, 2023

    @4ndrzej

    I am facing the same issue. Any news here?

  6. ephys commented on Feb 3, 2023

    @ephys
    Member

    None yet but I expect the complete rewrite of WHERE we're doing will fix this, as it's one of its goals (PR #15598)

  7. added theissue type on Mar 9, 2025
  8. removed
    type: bug
    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

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions