Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

model is not associated to theOtherModel when trying eager loading #3273

Closed
neekey opened this issue Mar 4, 2015 · 8 comments
Closed

model is not associated to theOtherModel when trying eager loading #3273

neekey opened this issue Mar 4, 2015 · 8 comments

Comments

@neekey
Copy link

neekey commented Mar 4, 2015

Father:

module.exports = function(sequelize, DataTypes) {
    var Father = sequelize.define("father", {
        name: {
            type: DataTypes.STRING,
            unique: true
        }
    }, {
        classMethods: {
            associate: function(models) {
                Father.hasMany( models.child, { as: 'children' })
            }
        }
    });

    return Father;
};

Child

module.exports = function(sequelize, DataTypes) {
    var Child = sequelize.define("child", {
        name: {
            type: DataTypes.STRING,
            unique: true
        }
    }, {
        classMethods: {
            associate: function(models) {
                Test.belongsTo( models.father );
            }
        }
    });

    return Child;
};

And my test case:

it( 'add a child', function( done ){

    DataProxy.model.father.create( { name: 'father' + Math.random() }).then(function( father ){

        return father.addChild( DataProxy.model.child.build( { name: 'child' + Math.random() } )).then(function( child ){
            Assert.equal( child.father_id, father.id );

            return father.getChildren().then(function( childrens ){
                Assert.lengthOf( childrens, 1 );

                return DataProxy.model.father.findAll( { include: [ DataProxy.model.child ]}).then( function( fathers ){
                    Assert.lengthOf( fathers[0].children, 1 );
                    done();
                }).catch(function( e ){
                    console.log( 'eager loading error: ', e );
                    throw e;
                });
            });
        });
    });
});

And keep getting this error:

eager loading error:  [Error: child is not associated to father!]

Frustrated : ( , did I miss something ? ( currently using sequelizeJS 2.0.1 with MySQL )

@mickhansen
Copy link
Contributor

DataProxy.model.father.findAll( { include: [ {model: DataProxy.model.child, as: 'children' ]}

If you are using an alias on the association you need to use it on the include aswell.

@neekey
Copy link
Author

neekey commented Mar 4, 2015

@mickhansen works! Sorry for my impatient : ) I finally find this tip in the Eager Loading section:

If an association is aliased (using the as option), you must specify this alias when including the model. Notice how the user's Tools are aliased as Instruments above. In order to get that right you have to specify the model you want to load, as well as the alias:

@neekey neekey closed this as completed Mar 4, 2015
@cullenr
Copy link

cullenr commented Apr 26, 2016

When using eager loading with the include:[{all:true}] option these as aliases do not appear to be used.

@janmeier
Copy link
Member

@cullenr Please open a new issue with a SSCCE instead of resurrecting old issues

rauligs pushed a commit to alphagov/pay-selfservice that referenced this issue Nov 9, 2016
  - It must contain the alias defined in the model as per sequelize
  issue: sequelize/sequelize#3273

  - Added 'find permissions' test. At the moment returning permissions
  as sequelize instances.

  - Fixed beforeEach to do sync in correct order, otherwise drop tables
  cannot be done due to existent rows in tables with foreign keys.
@JemarJones
Copy link

@mickhansen Wow thanks. These aliases do not work as i would expect them to :/

@ghost
Copy link

ghost commented Jul 17, 2017

Hmm... I just updated to Sequelize 4.3.2. I have many-to-many relationships that worked perfectly before the update. I don't use aliases anywhere in the code, and still it is giving me the error: "Unhandled rejection SequelizeEagerLoadingError: modelone is not associated to modeltwo!". Is there anything else than aliases that I should check to resolve this?

@smithaitufe
Copy link

I am in this same mess.
Please can someone me to figure this out
User.js model

module.exports = (sequelize, DataTypes) => {
    const User = sequelize.define('User', {
        id: {
            type: DataTypes.UUID,
            primaryKey: true,
            defaultValue: DataTypes.UUIDV4
        },
        username: {
            type: DataTypes.STRING(50),
            allowNull: false
        },
        firstName: {
            type: DataTypes.STRING(50),
            allowNull: false
        },
        lastName: {
            type: DataTypes.STRING(50),
            allowNull: false
        },
        about: {
            type: DataTypes.STRING(50),
        },
        avatar: {
            type: DataTypes.STRING(50),
        },
        passwordDigest: {
            type: DataTypes.STRING,
            allowNull: false
        }
    });
    User.associate = models => {
        User.hasMany(models.UserAddress)
        User.belongsToMany(model.Address, {through: model.UserAddress, foreignKey: "userId" })
    }
    return User;
}

then I have Address.js model

module.exports = function(sequelize,DataTypes){
    const Address = sequelize.define("Address", {
        id: {
            type: DataTypes.UUID,
            primaryKey: true,
            defaultValue: DataTypes.UUIDV4,
            allowNull: false
        },
        addressLine1: {
            type: DataTypes.STRING,
            allowNull: false
        },
        addressLine2: {
            type: DataTypes.STRING,
        },
        city: {
            type: DataTypes.STRING,
            allowNull: false
        },
        territory: {
            type: DataTypes.STRING,
            allowNull: false
        },
        country: {
            type: DataTypes.STRING,
            allowNull: false
        },
        firstName: {
            type: DataTypes.STRING(50),
            allowNull: false
        },
        lastName: {
            type: DataTypes.STRING,
            allowNull: false
        },
    });
    Address.associate = models => {
        Address.hasMany(models.UserAddress);
        Address.belongsToMany(models.User, { through: models.UserAddress, foreignKey: "addressId"});
    }
    return Address;
}

and UserAddress.js model

module.exports = function(sequelize,DataTypes){
    const UserAddress = sequelize.define("UserAddress", {
        id: {
            type: DataTypes.UUID,
            primaryKey: true,
            defaultValue: DataTypes.UUIDV4,
            allowNull: false
        },
        userId: {
            type: DataTypes.UUID,
            allowNull: false,
            references: {
                model: 'Users',
                key: 'id'
            }
        },
        addressId: {
            type: DataTypes.UUID,
            allowNull: false,
            references: {
                model: 'Addresses',
                key: 'id'
            }
        },
        addressTypeId: {
            type: DataTypes.UUID,
            allowNull: false,
            references: {
                model: 'AddressTypes',
                key: 'id'
            }
        },
        default: {
            type: DataTypes.BOOLEAN,
            defaultValue: false
        }
    });
    UserAddress.associate = models => {
        UserAddress.belongsTo(model.User, { targetKey: 'id', foreignKey: 'userId'})
        UserAddress.belongsTo(model.Address, { targetKey: 'id', foreignKey: 'addressId'})
        UserAddress.belongsTo(model.AddressType, { targetKey: 'id', foreignKey: 'addressTypeId'})
    }
    return UserAddress;
}

I have a function that is supposed to fetch user and included all addresses for that user. Unfortunately, this is not working.

const detailsAccountGet = async (req, res) => {
    let query = {};
    query.where = {
        id: req.params.id
    };
    query.include = [{
        model: db.Address
    }];
    
    let user = await db.User.findOne(query);
    return res.render("account/details.html", { user });
}

I get this error

SequelizeEagerLoadingError: Address is not associated to User!

This is part of my dependencies

    "pg": "^7.0.2",
    "pg-hstore": "^2.3.2",
    "sequelize": "^4.4.2"

Please I need help urgently, thanks

@ghost
Copy link

ghost commented Aug 1, 2017

@smithaitufe I don't know if this helps, but I solved my issue here:

https://stackoverflow.com/questions/45151194/sequelize-4-3-2-nm-many-to-many-association-unhandled-rejection-sequelizeeag

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants