I have 2 models separately named as "User" and "Test" in sequelize 5. Belongs To relation is given in Test model and it has userId from User model.
I have given the Belongs to relation in Test Model as below. Test Model
module.exports = (sequelize, DataTypes) => {
const Test = sequelize.define('Test', {
testId: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
validate: {
isInt: true
}
},
username: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
},
userId: {
type: DataTypes.INTEGER
}
}, {
tableName: 'tests'
});
Test.associate = (model) => {
Test.belongsTo(model.User, {
as: 'User',
foreignKey: 'userId',
targetKey: 'userId'
});
};
return Test;
};
User Model
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
userId: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
validate: {
isInt: true
}
},
username: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
},
createdAt: {
type: DataTypes.DATE,
allowNull: false,
},
});
console.log(sequelize.models);
return User;
};
ORM Query to find test model data as below
import db from '../../config/sequelize';
const { User, Test } = db;
Test.findAll({
limit,
include: [
{
model: User,
as: 'User'
}
]
})
Error Message: User is not associated to Test
Any idea how to associate it to get the user data in test ?
User
table definition hasuserId
field ? andUser.hasMany(model.Test {})
method ?