Sequelize: TypeError: hasOne is not a function

Sequelize: TypeError: hasOne is not a function

嗨,我是 Sequelize 的新手,hasOne 关联对我不起作用我正在尝试制作两个 tables table of

  1. 包含经销商名称和描述的经销商
  2. DealerProducts 包含经销商产品和价格以及 table1 作为 FKEY(我希望 hasOne 为我制作 FKEY)

所以我制作了 3 个文件,每个文件一个,然后是一个 index.js 文件来收集它们并建立相关关联

这些文件如下:

经销商-model.js

module.exports = (sequelize = require('../db')) => {

  const { DataTypes } = require('sequelize');

  const Dealer = sequelize.define('Dealer', {
    did: {
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
      allowNull: false,
      primaryKey: true
    },
    name: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true,
      validate: {
        len: [1, 50]
      }
    },
    description: {
      type: DataTypes.STRING,
      allowNull: true,
    },
  }, {
    tableName: 'dealers',
    timestamps: true,
    createdAt: 'created_at',
    updatedAt: 'updated_at',
    // paranoid: true
  })

  return Dealer;
}

经销商-产品-model.js

module.exports = (sequelize = require('../db')) => {
  const { DataTypes } = require('sequelize');

  const DealerProduct = sequelize.define('DealerProduct', {
    dpid: {
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
      allowNull: false,
      primaryKey: true
    },
    product_name: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true,
      validate: {
        len: [1, 100]
      }
    },
    type: {
      type: DataTypes.STRING,
      allowNull: true,
      validate: {
        len: [1, 100]
      }
    },
    description: {
      type: DataTypes.TEXT,
      allowNull: true
    },
    price: {
      type: DataTypes.DECIMAL(10, 2),
      allowNull: false
    },
    quantity: {
      type: DataTypes.INTEGER,
      allowNull: false
    }
  }, {
    tableName: 'dealer_products',
    timestamps: true,
    createdAt: 'created_at',
    updatedAt: 'updated_at',
    // paranoid: true
  })

  return DealerProduct;
}

然后index.js

module.exports = async (sequelize = require('../db')) => {
  const { DataTypes } = require('sequelize');
  const User = require('./user-model');
  const Dealer = require('./dealers-model');
  const DealerProduct = require('./dealer-products-model');
  User(sequelize)
  Dealer(sequelize)
  DealerProduct(sequelize)

  DealerProduct.hasOne(Dealer, {
    foreignKey: {
      type: DataTypes.UUID,
      allowNull: false,
      name: "dealers_did"
    }
  });

  Dealer.belongsTo(DealerProduct);

  sequelize.sync({alter: true}); //force: true
}

这正在为我的 postgres 创建 tables 但关联不起作用,因为我没有为 DealerProducts

创建 FKEY 列

这是我遇到的错误

TypeError: DealerProduct.hasOne 不是函数

我哪里错了?

更新

我的回答很简单,就是将 Dealer 和 DealerProduct 保存为变量,然后将这些变量用作 hasOne 示例:


 const dealer = Dealer(sequelize)
 const dealerProduct = DealerProduct(sequelize)

  dealer.hasOne(dealerProduct, {
    foreignKey: {
      type: DataTypes.UUID,
      allowNull: false,
      name: "dealers_did"
    }
  });

  dealerProduct.belongsTo(dealer);```

So this worked