How to solve problem with filter in Sequelize with belongsToMany association

Viewed 48

I using Sequelize with Node and Express.

I have created two models - User and Task with Many-to-Many associacion

const User = sequelize.define('user', {
    id: { type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true, allowNull: false },
    username: { type: Sequelize.STRING, allowNull: false, unique: true },
    password: { type: Sequelize.STRING, allowNull: false }
})

and

const Task = sequelize.define('task', {
    id: { type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true, allowNull: false },
    title: { type: Sequelize.STRING, allowNull: false }
})

Many-to-Many associacion

User.belongsToMany(Task, {
    through: "user_tasks",
    foreignKey: "userId",
    otherKey: "taskId"
})

Task.belongsToMany(User, {
    through: "user_tasks",
    foreignKey: "taskId",
    otherKey: "userId"
})

I'm trying to find tasks for user with id userId with following code:

const tasks = await Task.getTasks(
    { through: { where: { userId: request.userId } } }
    )

But i have an Error: TypeError: Task.getTasks is not a function"

1 Answers

If you want one users and their tasks do something like this?

const user = await User.findByPk(request.userId)
const userTasks = await user.getTasks()
Related