1

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.