Reputation: 329
I'm trying to make a API where:
I'm new to Sequelize so i'm struggling with this issue. (keep in mind that the one-to-many association works, but many-to-many doesn't)
Here's my models and migrations:
models/user.js:
'use strict';
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
name: DataTypes.STRING,
}, {});
User.associate = function(models) {
User.hasMany(models.Song, {
foreignKey: 'userId',
as: 'songs',
onDelete: 'CASCADE'
});
User.belongsToMany(models.Song, {
through: 'UserSongLike',
foreignKey: 'userId',
otherKey: 'songId',
as: 'songsList',
onDelete: 'CASCADE'
});
};
return User;
};
models/song.js:
'use strict';
module.exports = (sequelize, DataTypes) => {
const Song = sequelize.define('Song', {
userId: DataTypes.INTEGER,
title: DataTypes.STRING
}, {});
Song.associate = function(models) {
Song.belongsTo(models.User, {
foreignKey: 'userId',
as: 'songBy',
onDelete: 'CASCADE'
});
Song.belongsToMany(models.User, {
through: 'UserSongLikes',
foreignKey: 'songId',
otherKey: 'userId',
as: 'likedBy',
onDelete: 'CASCADE'
});
};
return Song;
};
models/usersonglike.js:
'use strict';
module.exports = (sequelize, DataTypes) => {
const UserSongLike = sequelize.define('UserSongLike', {
userId: DataTypes.INTEGER,
songId: DataTypes.INTEGER
}, {});
UserSongLike.associate = function(models) {
// associations can be defined here
};
return UserSongLike;
};
You can find the migrations here: https://gist.github.com/ExillustX/199b068912aae6368176718df13183e6
Now when i try to query the following code:
try {
const query = await models.UserSongLike.findAll({
include: [
{
model: models.User,
as: "users",
through: {
model: models.UserSongLike,
as: 'UserSongLikes',
}
}
]
});
console.log(query)
} catch (err) {
console.log(er)
}
I get an error: EagerLoadingError [SequelizeEagerLoadingError]: User is not associated to UserSongLike!
I'm not sure why this happens, could it be because i'm not adding table references in the migrations (or models)?
Any help is appreciated!
Upvotes: 1
Views: 609
Reputation: 1889
You need to associate User
and Song
, the UserSongLike
is an intermediate table that you don't need to declare here, the relation are created automatically by sequelize
.
You can try something like this:
try {
const query = await models.User.findAll({
include: [
{
model: models.Song,
}
]
});
console.log(query)
} catch (err) {
console.log(er)
}
Upvotes: 2