node.jsmodelsequelize.jsassociations

How to add associations if I have a custom foreign key using Sequelize?


I am trying to make an association between the model Listing and User provided below. I already created a custom foreign key on the Listing table with the column "user". How would I go about making this association? Because I am using a controller with the following logic. But I get the "SequelizeEagerLoadingError" so I know it has something to do with associations. Thank you!

const listings = await Listing.findAll({
    include: [{
        model: User,
        attributes: ['name', 'email']
    }]
});

Listing Model

const Sequelize = require('sequelize');
const {sequelize} = require('../database/connect.js');
const User = require('./User.js');

const Listing = sequelize.define('listings', {
    // Column Definitions ...
    user: {
        type: Sequelize.DataTypes.INTEGER,
        allowNull: false,
        validate: {
            notEmpty: {
                args: [true],
                msg: 'Must Provide Listing User'
            }
        },
        references: { 
            model: User, 
            key: 'id'
        }
    }
}, {timestamps: true, freezeTableName: true, hooks: {
    
}});

// **Define the Association Here ...**

async function syncTable() {
    await Listing.sync();
    console.log(`Listing Table Created if it doesn't exist. And doing nothing if it already exists`);
}

syncTable();

module.exports = Listing;

User Model

const Sequelize = require('sequelize');
const {sequelize} = require('../database/connect.js');
const bcrypt = require('bcryptjs');
const path = require('node:path');
const fs = require('node:fs');
const Listing = require('./Listing.js');

const User = sequelize.define('users', {
     // Column Definitions ...
}, {timestamps: true, freezeTableName: true, hooks: {
    
}});

// Define the Association Here ...

async function syncTable() {
    await User.sync();
    console.log(`User Table Created if it doesn't exist. And doing nothing if it already exists`);
}

syncTable();

module.exports = User;

I tried the following associations but not sure if they are correct

Listing.belongsTo(User, {foreignKey: 'user', targetKey: 'id', as: 'userDetails'}); When I use this code 👆, I don't get any error.

User.hasMany(Listing); When I use this code 👆, I do get an error. It says that their is a problem in the import/export of the Model but thats not true because it said the same thing for the Listing association but eventually after playing around with the options object that error went away.


Solution

  • You just need to define both associations with the same foreignKey option and its value, see my answer here:

    Listing.belongsTo(User, { foreignKey: 'user', as: 'userDetails'});
    User.hasMany(Listing, { foreignKey: 'user', as: 'listings' });