Answer the question
In order to leave comments, you need to log in
What is the correct way to make a request through sequelize?
Hello!
Please tell me, in my project there is a many-to-many relationship:
const User = sequelize.define('user', {
id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true},
login: {type: DataTypes.STRING, unique: true},
password: {type: DataTypes.STRING},
role: {type: DataTypes.STRING, defaultValue: 'USER'},
img : {type: DataTypes.STRING, defaultValue: 'default_avatar.jpg'},
deleted: {type: DataTypes.BOOLEAN, defaultValue: false},
})
const Brain = sequelize.define('brain', {
id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true},
name: {type: DataTypes.STRING, unique: true},
img: {type: DataTypes.STRING, allowNull: false},
description: {type: DataTypes.TEXT, defaultValue: 'test'},
})
const UserBrain = sequelize.define('user_brain', {
id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true},
userId: {type: DataTypes.INTEGER, references: {model: User, key: 'id'}},
brainId: {type: DataTypes.INTEGER, references: {model: Brain, key: 'id'}}
})
User.belongsToMany(Brain, {through: UserBrain, as: 'brain'})
Brain.belongsToMany(User, {through: UserBrain, as: 'user'})
async getOneUserBrains(req, res, next) {
try {
const {id} = req.params
const userBrain = await Brain.findAll(
{
include: [{
model: User,
as: 'user',
where: {'id': id},
attributes: ['id']
}]
},
)
return res.json(userBrain)
} catch (e) {
next(ApiError.badRequest(e.message))
}
}
select "brainId", b.name, count("brainId") as popularity from user_brains
join brains b on b.id = user_brains."brainId"
group by "brainId", b.name
order by count("brainId") desc
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question