D
D
ddgryaz2021-07-09 20:29:24
JavaScript
ddgryaz, 2021-07-09 20:29:24

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'})


I have already accessed the linking table, as follows:
Example

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))
        }

    }



Now, I can't figure it out.
Now I need to get some data, in raw form I do it with the following SQL query:
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


How to correctly form this query through sequelize?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question