Search code examples
postgresqlforeign-keyssequelize.js

hasMany foreignKey not working in Sequelize


I have some models - kanban_cards, kanban_checklists, kanban_checkitems.

kanban_cards model:

export default (sequelize, DataTypes) => {
  return sequelize.define('kanban_card', {
    id: {
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
      primaryKey: true,
    },
    name: {
      type: DataTypes.STRING,
      allowNull: false
    },
    label: {
      type: DataTypes.STRING,
      allowNull: true,
    },
    listId: {
      type: DataTypes.UUID,
      allowNull: false
    },
    ...
  })
}

kanban_checklist:

export default (sequelize, DataTypes) => {
  return sequelize.define('kanban_checklist', {
    id: {
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
      primaryKey: true,
    },
    name: {
      type: DataTypes.STRING,
      allowNull: false
    },
    cardId: {
      type: DataTypes.UUID,
      allowNull: false,
    }
  })
}

And the association is:

const models = {
  KanbanCards: KanbanCards(sequelize, Sequelize.DataTypes),
  KanbanChecklists: KanbanChecklists(sequelize, Sequelize.DataTypes),
  ...
}
...
models.KanbanCards.hasMany(models.KanbanChecklists, { as: 'checklists', foreignKey: 'cardId' })
models.KanbanChecklists.belongsTo(models.KanbanCards)

It works fine if I use findAll, but if I try to create, it doesn't work.

It says. column "kanbanCardId" of relation "kanban_checklists" does not exist

I am going to use cardId rather than kanbanCardId.

I tried to set references to cardId, but it didn't work either.


Solution

  • If you indicated an explicit foreign key column in hasMany you should do the same for the other part - belongsTo:

    models.KanbanChecklists.belongsTo(models.KanbanCards, { foreignKey: 'cardId' })
    

    Otherwise Sequelize generate a foreign key name itself like in your case kanbanCard+id:

    The name of the foreign key in the join table (representing the target model) or an object representing the type definition for the other column (see Sequelize.define for syntax). When using an object, you can add a name property to set the name of the column. Defaults to the name of target + primary key of target