I have a table that joins users and inspections that is called userinspections. When I query only the join table, the primary key id is not included in the attributes. The migration looks like this:
'use strict';
module.exports = {
up: function(queryInterface, Sequelize) {
return queryInterface.createTable('UserInspections', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
user_id: {
type: Sequelize.INTEGER
},
inspection_id: {
type: Sequelize.INTEGER
},
created_at: {
allowNull: false,
type: Sequelize.DATE
},
updated_at: {
allowNull: false,
type: Sequelize.DATE
},
deleted_at: {
allowNull: true,
type: Sequelize.DATE
}
});
},
down: function(queryInterface, Sequelize) {
return queryInterface.dropTable('UserInspections');
}
};
The model definition looks like this:
import baseModel from 'lib/models/model';
export default function(sequelize, DataTypes) {
const name = 'UserInspection'
const columns = {
user_id: DataTypes.INTEGER,
inspection_id: DataTypes.INTEGER
};
const options = {
classMethods: {
associate: function(models) {
// associations can be defined here
}
}
};
const UserInspection = baseModel({ name, columns, options }, sequelize);
return UserInspection;
};
I am wrapping every model in that baseModel just to add some standard class methods to every model. This doesn't cause an issue with any other model.
I am simply expecting the id column to be returned.
The id column is omitted from the query results. I can fix this by adding id to the column names in the model definition, but then I have to specify an id when inserting, which is not desirable.
Dialect: postgres
Database version: 9.5
Sequelize version: 3.21.0
By default sequelize assumes the primary key for the join table is a composite key of userid, inspectionid. You can circumvent that by adding id (as you've tried) - but you need to mark the id as an ai primary key:
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
}
Most helpful comment
By default sequelize assumes the primary key for the join table is a composite key of userid, inspectionid. You can circumvent that by adding id (as you've tried) - but you need to mark the id as an ai primary key: