【问题标题】:findAll sequelize with model returning odd valuesfindAll 与模型返回奇数值续集
【发布时间】:2020-11-05 17:28:43
【问题描述】:

感谢:https://stackoverflow.com/a/64702949/14585149

我希望列出我在 mysql 数据库中的所有交易以及相关用户。

我有 2 个表/模型:Transaction & User

交易:

module.exports = function(sequelize, DataTypes) {
  return sequelize.define('transactions', {
    transaction_id: {
      type: DataTypes.INTEGER(11),
      allowNull: false,
      primaryKey: true
    },
    user_id: {
      type: DataTypes.INTEGER(11),
      allowNull: false,
      references: {
        model: 'users',
        key: 'user_id'
      }
    },
    account_id: {
      type: DataTypes.INTEGER(11),
      allowNull: false,
      references: {
        model: 'accounts',
        key: 'account_id'
      }
    },




 }, { tableName: 'transactions' }); };

用户:

module.exports = function(sequelize, DataTypes) {
  return sequelize.define('users', {
    user_id: {
      type: DataTypes.INTEGER(11),
      allowNull: false,
      primaryKey: true,
      references: {
        model: 'recipients',
        key: 'created_by'
      }
    },
    contact_id: {
      type: DataTypes.INTEGER(11),
      allowNull: true,
      references: {
        model: 'contacts',
        key: 'contact_id'
      }
    }, }, {
    tableName: 'users',
    timestamps: false
  });
};

我已经建立了关联:

Transaction.hasOne(User, {foreignKey:'user_id'});
User.belongsTo(Transaction, {foreignKey:'user_id'});

我的代码是:

api.get('/trx', async (req, res) => {

   
  Transaction.findAll({
    attributes: ['transaction_id','user_id','account_id'],
    include: [{
      model: User,
      attributes: ['user_id']}]

  })
  .then(intrx => res.json(intrx))
  
  .catch(res.catch_error)


});

结果:

[
  {
    "transaction_id": 1,
    "user_id": 4,
    "account_id": 1,
    "user": {
      "user_id": 1
    }
  },
  {
    "transaction_id": 2,
    "user_id": 4,
    "account_id": 75,
    "user": {
      "user_id": 2
    }
  }
]

为什么 user_id 的值不同? 我期待第一个结果中的 user_id = 4 而不是 1 和第二个结果中的 user_id = 4。

我做错了什么?

【问题讨论】:

  • 显示模型定义。我不明白Transactionuser_id 字段或User
  • 我已将 2 个模型添加到最初的问题中。

标签: node.js express sequelize.js


【解决方案1】:

你应该像这样反转你的关联:

Transaction.belongsTo(User, {foreignKey:'user_id'});
User.hasOne(Transaction, {foreignKey:'user_id'});

因为Transaction 具有指向User 的链接,即属于它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-05
    • 1970-01-01
    • 2020-03-07
    • 2019-05-20
    • 1970-01-01
    • 2019-07-03
    • 1970-01-01
    • 2020-04-16
    相关资源
    最近更新 更多