sails-hook-sequelize-blueprints icon indicating copy to clipboard operation
sails-hook-sequelize-blueprints copied to clipboard

Cannot get it work with hasMany+belongsTo associations.

Open vladuva opened this issue 8 years ago • 3 comments

I have two models: User and Trade and I have these associations:

User.hasMany(Trade);
Trade.belongsTo(User);

I get blueprint error when starting Sails:

node_modules/sails-hook-sequelize-blueprints/index.js:338
              var alias = foreign.as || foreign.name || foreign;
                                 ^

TypeError: Cannot read property 'as' of undefined

If I explicitly define foreignKey:

User.hasMany(Trade, { foreignKey: { name: 'User', allowNull: false }});

I get a Sequelize error:

node_modules/sequelize/lib/associations/helpers.js:7
    throw new Error(
    ^

Error: Naming collision between attribute 'User' and association 'User' on model Trade. To remedy this, change either foreignKey or as in your association definition

Did I do something wrong or is there something wrong with blueprints?

vladuva avatar Oct 04 '15 22:10 vladuva

Thanks for the feedback,

This hook uses the alias to match the association, you should specify the alias as for the foreign key.

Take a look at this samples

https://github.com/cesardeazevedo/sails-hook-sequelize-blueprints/blob/master/test/fixtures/sampleapp/api/models/image.js#L15-L22

https://github.com/cesardeazevedo/sails-hook-sequelize-blueprints/blob/master/test/fixtures/sampleapp/api/models/user.js#L19-L27

Let me know if you got it.

cesardeazevedo avatar Oct 05 '15 22:10 cesardeazevedo

I did not. I extended the definition according to your example:

User.hasMany(Trade, {
  as: 'Trades',
  foreignKey: {
    name: 'UserId',
    as: 'Trades',
  },
});
Trade.belongsTo(User, {
  as: 'User',
  foreignKey: {
    name: 'UserId',
    as: 'User',
  },
});

There are no errors during startup, but there's an error when I try /users/list"

SequelizeDatabaseError: ER_BAD_FIELD_ERROR: Unknown column 'Trades.daySequence' in 'field list'

Do I still do something wrong?

Why sails-hook-sequelize-blueprints cannot just work with Sequelize default assignment setup?

vladuva avatar Oct 06 '15 14:10 vladuva

It's seems there's other error causing this.

this hook doesn't loads the sequelize actually, https://github.com/festo/sails-hook-sequelize does it

there's something wrong with daySequence column, have you force the sequelize syncronization at config/models.js?

module.exports.models = {
    migrate: 'drop'
}

can i have a full sample to reproduce it?

cesardeazevedo avatar Oct 06 '15 16:10 cesardeazevedo