Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

262
Visualizações
Setting custom column names for foreign Keys in Sequelize Node.js

sequelize noobie here so sorry in advance. I am making some Table associations in my app between users posts and comments

Comments Model

import { DataTypes } from 'sequelize';


export const comment = (db) => {
  db.define('comment', {
    commentContent: {
      type: DataTypes.TEXT,
      allowNull: false
    }
  });
}
export const setModelRelationships = (db) => {
    const { user, post, comment } = db.models

    user.hasMany(post);
    user.hasMany(comment);

    post.belongsTo(user);
    post.hasMany(comment);

    comment.belongsTo(post);
    comment.belongsTo(user);
}

Checking my db comments has 6 columns:

id | commentContent | createdAt | updatedAt | postId | userId |

if I want to give the postId a custom name such as: commentedOnPostId how can I do this with Sequelize?

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You can use foreignKey option in associations like this:

post.hasMany(comment, { foreignKey: 'commentedOnPostId' });
comment.belongsTo(post, { foreignKey: 'commentedOnPostId' });

It's important to indicate the same foreignKey option value in both associations.

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda