Skip to content

find({ ... }) doesn't intelligently handle associations #293

@notheotherben

Description

@notheotherben

Currently it is impossible to use a find({ association: instance }) condition correctly, as such conditions are passed directly to node-sql-query without any kind of intelligent filtering.

Repro

var person = db.define('person', {
    name: String
});

var pet = db.define('pet', {
    name: String
});

pet.hasOne('owner', person, {
    required: true
});

// Load some stuff into the database...

person.get(1, function(err, person) {
    pet.find({ owner: person }, function(err, pets) {
        // Generates an invalid SQL query
    });
});

Problem

Instead of using owner_id, and the id of the passed person, to run the query (as one would expect) we find node-orm2 passing the conditions in raw form to node-sql-query (not sql-query's fault, since it is supposed to be low level) which results in a SQL query like the following:

SELECT `id`, `name`, `owner_id` FROM `pet` WHERE `owner` = `id` = 1, `name` = 'John Doe'

What we would expect it to do is generate a SQL query like this:

SELECT `id`, `name`, `owner_id` FROM `pet` WHERE `owner_id` = 1

Possible Solutions

  • Preprocess conditions as they are received, mapping conditions who's identifiers map to properties on the current model to the identifiers required to identify the relationship.
  • Preprocess conditions, mapping if the value of a condition is an Instance object and the condition identifier maps to a property on the current model.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions