0

I've been having trouble for a while trying to properly get my associations working. I have an Auctions model and a Bids model, the Auctions model has many Bids. There is the foreign Key "BidId" on Auctions that is linked to "bid_id" on Bids.

Auction.js

const Sequelize = require('sequelize');
const sequelize = require('../config/database');

const User = require('./User');
const Status = require('./Status');
const Vehicle = require('./Vehicles')
const Bids = require('./Bids');
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.INTEGER
  }
});

module.exports = 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.hasOne(Auction, {foreignKey: 'BidId'}) // Bids is the source, Auction is the target
Auction.hasMany(Bids);
module.exports = Bids

When I use the following query: const findBidOnAuction = () => {Auction.findAll( {where:{BidId:1},include:[{model:Bids}]}).then(data => console.log("result", data))} I receive the error: Unhandled rejection SequelizeDatabaseError: column GSMBids.GSMAuctionAucId does not exist

I have no idea where GSMBids.GSMAuctionAucId is supposed to come from, I assume Sequelize by default expects a column with that name when using associations but that doesn't make sense because I defined the columns that are linked specifically. It looks like It's trying to link auc_id but I don't want that.

edit: and if I switch the query around and do this: const findBidOnAuction = () => {Bids.findAll( {where:{bid_id:1},include:[{model:Auction}]}).then(data => console.log("result", data))}

I get Unhandled rejection SequelizeEagerLoadingError: GSMAuction is not associated to GSMBids!

Amon
  • 2,725
  • 5
  • 30
  • 52

1 Answers1

1

I suspect Sequelize doesn't know which field in Auction is associated with Bids. You might try:

Auction.hasMany(Bids,
         {
         sourceKey : "BidId",  // auction
         foreignKey: "bid_id"  // bids
         });

Even if the error doesn't recur, check the generated SQL and make sure the join is correct!

KenOn10
  • 1,743
  • 1
  • 9
  • 10