Can't set up foreign key with sequelize

Viewed 20

I'm using sequelize with mySQL on a node server. I'm creating a tournament score database. I've created models for Participant and Scores. I've tried to make a foreign key for Scores related to Participant_id so that the participant data gets pulled when there is a GET request for Scores.

I've tried these examples as my index.js file

const Participant = require('./Participant')
const Scores = require('./Scores')

Scores.belongsto(Participant)

module.exports = { Participant, Scores };

or

const sequelize = require('../config/connections')
const Participant = require('./Participant')
const Scores = require('./Scores')

Participant.hasOne(Scores, {
    foreignKey: 'participant_id'
})

module.exports = { Participant, Scores};

Scores module

const { Model, DataTypes } = require('sequelize');
const sequelize = require('../config/connections');
const Participant = require('./Participant')

class Scores extends Model {}

Scores.init(
    {
        id: {
            type: DataTypes.INTEGER,
            allowNull: false,
            primaryKey: true,
            autoIncrement: true,
        },
        total_score: {
            type: DataTypes.FLOAT(2),
        },
    },
    {
        sequelize,
    }
)

//I've removed and included this trying to get foreign keys to work
EmptyScores.associate = function (models) {
EmptyScores.belongsTo(models.Participant)
}

module.exports = Scores

Nothing seems to add a foreign key to scores. Any help would be appreciated.

1 Answers

My associations always map the specific source and foreign keys, and both keys (id and participant_id) are defined in the models.

Participant.hasOne(Scores, {
  // from Scores
  foreignKey: 'participant_id',
  // from Participant
  sourceKey: 'id' 
});
Related