Amon
Amon

Reputation: 2951

Able to make migration with associations but not able to query with associations (association not found)

I've built a database with a couple tables that are associated with each other: Auction and Bids. Each Auction should have many Bids and each Bid should have only one Auction. I made a migration fine to add foreignKeys but when I try to look up a certain Bid on an Auction I receive a SequelizeEagerLoadingError: Bids is not associated to Auctions! error.

migrations file:

'use strict';
module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.addColumn(
      'Auctions', // name of target model
      'BidId',
      {
        type: Sequelize.INTEGER,
        references:{
          model: "bids",
          key: "bid_id",
        },
      },
    );
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable('Auction');
  }
};

bids.js

const Sequelize = require('sequelize');


// const resolver = require('graphql-sequelize');
const sequelize = require('../config/database');
const Auction = require('./Auction');

const tableName = 'bids';
const Bids = sequelize.define('Bids', {
  bid_id: {
    type: Sequelize.INTEGER,
    autoIncrement: true,
    primaryKey: true
  },
  createdAt: {
   type: Sequelize.DATE,
   // defaultValue: Sequelize.NOW
  },
  updatedAt: {
    type: Sequelize.DATE,
    defaultValue: Sequelize.NOW,
  },
  amount: {
    type: Sequelize.INTEGER
  },
  bid_amount: {
    type:Sequelize.STRING
  },
  bid_no: {
    type: Sequelize.UUID,
    defaultValue: Sequelize.UUIDV4,
  },
}, 
{tableName})

Bids.associate = () => {
  Bids.hasOne(Auction, {foreignKey:"BidId"})
};

auction.js

const Sequelize = require('sequelize');
const sequelize = require('../config/database');
const tableName = 'Auctions';
const Auction = sequelize.define('Auctions', {
  auc_id: {
    type: Sequelize.UUID,
    defaultValue: Sequelize.UUIDV4, // generate the UUID automatically
    primaryKey: true,
  },
  features: {
    type: Sequelize.JSONB,
  },
  bid_amount: {
    type:Sequelize.STRING
  },
  BidId: {
    type: Sequelize.UUID,
  }
}, { tableName });

Auction.hasMany(Bids, {foreignKey: 'BidId'}) 

module.exports = Auction

query.js

const findBidOnAuction = () => {Auction.findOne({where:{BidId:2}, include:[{model:Bids}]}).then(data => console.log("result", data))}

How do I properly associate these tables?

edit: Also on pgAdmin I can that the relationship exists, BidId is a foreignKey on Auction linked to bid_id on Bids

Upvotes: 0

Views: 40

Answers (1)

Ellebkey
Ellebkey

Reputation: 2301

I do the following for add a foreignKey on migrations:

1.I create a migration for the parent model with a ref function. const TABLE_NAME = 'parent';

function up(queryInterface, Sequelize) {
  return queryInterface.createTable(
    TABLE_NAME, //Bid model
    {
      //attributes
    },
  );
}

function down(queryInterface, Sequelize) {
  return queryInterface.dropTable(TABLE_NAME);
}

function ref(Sequelize) {
  return {type: Sequelize.STRING(2), references: {model: TABLE_NAME, key: 'id'}}; // 'id' here is your parent (Bids) primary key
}

module.exports = {up, down, ref};

2.On the child model where you are going to add the reference, you import the ref function and added like this, so your migration actually knows which model are you refering:

const {ref: REF_Model} = require('name-of-your-migration-file'); //import model


  async function up(queryInterface, Sequelize){
    await queryInterface.addColumn('Auctions', 'BidId', {...REF_Model(Sequelize), allowNull: true});
  }

  async function down(queryInterface){
    await queryInterface.removeColumn('Auctions', 'BidId');
  }

module.exports = {up, down};

Upvotes: 1

Related Questions