J
J
jenya77712020-01-11 15:12:07
PostgreSQL
jenya7771, 2020-01-11 15:12:07

How to execute group in Sequelize?

Hello, there are 3 tables:
Users:

const users = sequelize.define('users', {
    login: {
        type: Sequelize.STRING,
        allowNull: true,
    },
    email: {
        type: Sequelize.STRING,
        allowNull: true
    },
    password: {
        type: Sequelize.STRING,
        allowNull: false
    }
})

Messengers:
const messengers = sequelize.define('messengers', {
    user_id: {
        type: Sequelize.INTEGER,
        allowNull: false,
        foreignKey: true
    },
    messenger_id: {
    type: Sequelize.STRING,
    allowNull: true
    },
    login: {
    type: Sequelize.STRING, 
    allowNull: true
    }
})

Messages:
const messengerMessages = sequelize.define('messenger_messages', {
    messenger_id: {
        type: Sequelize.INTEGER,
        allowNull: false,
        foreignKey: true
    },
    text: {
        type: Sequelize.TEXT,
        allowNull: true
    }
})

And a bunch of these tables:
users.hasMany(messengers, { foreignKey: 'user_id', as: 'userMessenger' })
messengers.belongsTo(users, { foreignKey: 'user_id', as: 'userMessenger' })

messengers.hasMany(messengerMessages, { foreignKey: 'messenger_id', as: 'messengerMessages' })
messengerMessages.belongsTo(messengers, { foreignKey: 'messenger_id', as: 'messengerMessages' })

And I need to group the data so that I get arrays with user messages, by the users.id field.
I made many attempts, re-read a dozen articles, but did not understand how to implement it, tell me, can anyone come across a similar one?
await models.messengerMessages.findAll({
            include: [{
                model: models.messengers,
                as: 'messengerMessages',
                include: [{
                    model: models.users,
                    as: 'userMessenger',
                }]
            }],
            group: ['messengerMessages->userMessenger.id']
        })

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