Sequelize关联已存在于pgAdmin中,但在查询过程中一直在寻找未知列

时间:2019-04-03 15:34:56

标签: node.js sequelize.js pgadmin

一段时间以来,我一直在尝试正确地使我的关联正常工作。我有一个拍卖模型和一个投标模型,拍卖模型有很多投标。拍卖中有一个外键“ BidId”链接到了出价上的“ bid_id”。

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

当我使用以下查询时: const findBidOnAuction = () => {Auction.findAll( {where:{BidId:1},include:[{model:Bids}]}).then(data => console.log("result", data))} 我收到错误消息:Unhandled rejection SequelizeDatabaseError: column GSMBids.GSMAuctionAucId does not exist

我不知道GSMBids.GSMAuctionAucId的来源,我假设Sequelize在默认情况下会在使用关联时期望具有该名称的列,但这没有意义,因为我定义了专门链接的列。看起来它正在尝试链接auc_id,但我不希望这样。

edit:如果我切换查询并执行以下操作: const findBidOnAuction =()=> {Bids.findAll({其中:{bid_id:1},包括:[{model:Auction}]})。then(data => console.log(“ result”,data))}

我得到Unhandled rejection SequelizeEagerLoadingError: GSMAuction is not associated to GSMBids!

1 个答案:

答案 0 :(得分:1)

我怀疑Sequelize不知道Auction中的哪个字段与出价相关。您可以尝试:

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

即使错误不再发生,也请检查生成的SQL并确保联接正确!