Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

263
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda