Skip to content

Reverse associations are not using the correct field in JOIN clause #446

@carlosafonso

Description

@carlosafonso

I came accross this using orm 2.1.3, mysql 2.0.1 and node 0.10.20.

Consider two tables, drivers and cars. Each car belongs to a single driver, and drivers can have as many cars as they wish, so cars relates to drivers by means of column driverId.

These models could be defined as follows:

    var Driver = db.define("drivers", {
        name: String,
        age: Number
    }, {
        id: "driverId"
    });

    var Car = db.define("cars", {
        make: String,
        year: Number
    }, {
        id: "carId"
    });

Additionally, the hasOne() relationship is also defined:

Car.hasOne("owner", Driver, {autoFetch: true, field: "driverId", reverse: "cars"});

The strange behaviour occurs when attempting to retrieve data using the findBy*() functions. Invoking:

Car.findByOwner({name: "Lauren"})

Produces the following query:

SELECT `t1`.`carId`, `t1`.`make`, `t1`.`year`, `t1`.`driverId` FROM `cars` `t1` JOIN `drivers` `t2` ON `t2`.`driverId` = `t1`.`driverId` WHERE `t2`.`name` = 'Lauren'

Which as far as I know is fine. However, invoking a similar query on the reverse association:

Driver.findByCars({make: "Fiat"})

Produces this:

SELECT `t1`.`driverId`, `t1`.`name`, `t1`.`age` FROM `drivers` `t1` JOIN `cars` `t2` ON `t2`.`carId` = `t1`.`driverId` WHERE `t2`.`make` = 'Fiat'

Notice how the JOIN clause is matching t2.carId with t1.driverId, whereas it should be t2.driverId and t1.driverId.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions