Thursday 29 August 2019

Sequelize always needs a primary key on join where there is no primary key '_indcies.id' is not found'

Hi all,Been in a full goolge circle for me. Maybe this is a limitation in sequelize but I'm asking hoping my assumption is wrong.When I learned databases in college it was my understanding you can use an index table where a pair of keys can become the primary key. So this is great when you need a 3 way association (this example uses 2 but assume 3)The modelsconst Access = sequelize.define('access', {id: {type: Sequelize.INTEGER.UNSIGNED,autoIncrement: true,primaryKey: true},label: {type: Sequelize.STRING},weight: {type: Sequelize.INTEGER}});​const UserAccessIndex = sequelize.define('user_access_index', {access_id: {type: Sequelize.INTEGER.UNSIGNED,index: true},user_id: {type: Sequelize.INTEGER.UNSIGNED,index: true}});​const User = sequelize.define('user', {id: {type: Sequelize.INTEGER.UNSIGNED,autoIncrement: true,primaryKey: true},account_status_id: {type: Sequelize.INTEGER.UNSIGNED,index: true},access_id: {type: Sequelize.INTEGER.UNSIGNED,index: true},date_created: {type: Sequelize.DATE,defaultValue: Sequelize.literal('NOW()'),allowNull: false},date_modified: {type: Sequelize.DATE,defaultValue: Sequelize.literal('NOW()'),allowNull: false},date_subscription_expiration: {type: Sequelize.DATE,defaultValue: null,allowNull: true},date_last_login: {type: Sequelize.DATE,defaultValue: Sequelize.NOW,allowNull: true}});Access.hasMany(UserAccessIndex, { foreignKey: 'access_id' });UserAccessIndex.belongsTo(Access);User.hasMany(UserAccessIndex, { foreignKey: 'user_id' });UserAccessIndex.belongsTo(User);​When you join & use that modelawait User.findOne({attributes: ['id', 'account_status_id'],where: {id: userId,account_status_id: CONSTANTS.VALID_ACCOUNT_ID},include: [{attributes: ['access_id', 'user_id'],model: UserAccessIndex}]});​I get something like 'user_access_indcies.id' is not found. Sequelize injects the need for the primary key. When I debug there is 'originalAttributes' (which are correct) but then the 'attributes' .Am I missing something here or is sequelize just this opinionated?

Submitted August 29, 2019 at 12:45PM by bigorangemachine

No comments:

Post a Comment