Search for record in another table with mysql and sequelize

Asked

Viewed 323 times

0

How to search the column record nome on the table categoria, for id that was saved in the table postagens?

const db = require('./db')

const Post = db.sequelize.define('postagens', {
    titulo: {
        type: db.Sequelize.STRING
    },
    slug: {
        type: db.Sequelize.STRING
    },
    descricao: {
        type: db.Sequelize.TEXT
    },
    conteudo: {
        type: db.Sequelize.TEXT
    },
    categoria: {
        type: db.Sequelize.STRING
    }
})


module.exports = Post

1 answer

0

In order to be able to do this "Join", you must have the two associated models, so postagens.categoria will be a Foreign key.

Then you can give one include in the findAll of your Post indicating to include the model of its categoria, indicating a alias (optional) and the desired attribute.

Post.findAll({
    include: [{
        model: Categoria,
        as: 'categoria', // Caso você tenha dado um "alias" na associação
        attributes: ['nome']
    }]
})

The answer will be something like:

[
    {
        // Campos do seu modelo Post
        "titulo": "Titulo",
        "slug": "Slug",
        "descricao": "Descrição",
        "conteudo": "Conteúdo",
        "categoriaId": "ID da categoria",

        // O que você colocou no includes:
        "categoria": {
            "nome": "Nome da categoria"
        }
    }
]

You can see some more details in this document on Github.

I found no examples in the official documentation of Sequelize, but you can see the documentation on associations to better understand how it works.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.