【问题标题】:N:M association error when using include.through使用 include.through 时出现 N:M 关联错误
【发布时间】:2015-11-15 07:53:10
【问题描述】:

场景

一个用户可以有很多标签对象。一个 Tag 对象属于一个用户。一个标签有许多事务。一个事务属于一个标签。用户有很多交易。一个事务可以有多个用户。

型号

var User = sequelize.define('User', {
      id: {
          type: Sequelize.BIGINT,
          autoIncrement: true,
          primaryKey: true
      },

      ...

  }, { timestamps: false, freezeTableName: true, tableName: 'register'});


var Tag = sequelize.define('Tag', {
      tagId: {
          type: Sequelize.STRING(50),
          primaryKey: true,
          allowNull: false
      },

      ...

  }, { timestamps: false, freezeTableName: true, tableName: 'tag'});


var Transaction = sequelize.define('Transaction', {
      id: {
          type: Sequelize.BIGINT,
          autoIncrement: true,
          primaryKey: true
      },
      active: {
          type: Sequelize.BOOLEAN,
          defaultValue: true
      }
  }, { timestamps: false, freezeTableName: true, tableName: 'transaction'});


var UserTx = sequelize.define('UserTx', {
    id: {
        type: Sequelize.BIGINT,
        autoIncrement: true,
        primaryKey: true
    }
  },
  { timestamps: false, freezeTableName: true, tableName: 'user_transaction'});

关系

User.hasMany(Tag, {foreignKey: 'owner_id', foreignKeyConstraint: true});
Tag.belongsTo(User, {foreignKey: 'owner_id', foreignKeyConstraint: true});

Tag.hasMany(Transaction, {foreignKey: 'tag_id', foreignKeyConstraint: true});
Transaction.belongsTo(Tag, {foreignKey: 'tag_id', foreignKeyConstraint: true});

User.belongsToMany(Transaction, {through: {model: UserTx, unique: false}, foreignKey: 'user_id'});
Transaction.belongsToMany(User, {through: {model: UserTx, unique: false}, foreignKey: 'tx_id'});

问题

我正在尝试返回给定用户拥有的 Tag 对象列表,以及用户与其关联的 Transactions 的 Tag 对象。在纯 SQL 中:

select * from tag 
left outer join transaction on tag."tagId" = transaction.tag_id 
left outer join user_transaction on transaction.id = user_transaction.tx_id 
where tag.owner_id = ? or user_transaction.user_id = ?

我当前的 Sequelize 查询:

Tag.findAll({
      where: { owner_id: userId }, // missing OR user_transaction.user_id = userId
      include: [{
        model: Transaction,
        attributes: ['id'],
        through: {model: UserTx, where: {user_id: userId}, attributes: ['user_id', 'tx_id']},
        where: {
          active: true
        },
        required: false, // include Tags that do not have an associated Transaction
      }]
})

调用此查询时,我收到以下错误:

Unhandled rejection TypeError: Cannot call method 'replace' of undefined
at Object.module.exports.removeTicks (/site/services/node_modules/sequelize/lib/utils.js:343:14)
at Object.module.exports.addTicks (/site/services/node_modules/sequelize/lib/utils.js:339:29)
at Object.QueryGenerator.quoteIdentifier (/site/services/node_modules/sequelize/lib/dialects/postgres/query-generator.js:843:20)
at generateJoinQueries (/site/services/node_modules/sequelize/lib/dialects/abstract/query-generator.js:1207:72)
at Object.<anonymous> (/site/services/node_modules/sequelize/lib/dialects/abstract/query-generator.js:1388:27)
at Array.forEach (native)
at Object.QueryGenerator.selectQuery (/site/services/node_modules/sequelize/lib/dialects/abstract/query-generator.js:1387:10)
at QueryInterface.select (/site/services/node_modules/sequelize/lib/query-interface.js:679:25)
at null.<anonymous> (/site/services/node_modules/sequelize/lib/model.js:1386:32)

在 removeTicks 函数中设置断点并在“s”(列名属性)上设置监视,我注意到以下内容:

s = "Transactions"
s = "Transactions.id"
s = "Transactions.undefined" // should be Transactions.UserTx ?
s = "user_id"
s = "Transactions.undefined.user_id"
s = "Transactions.undefined"
s = "tx_id"
s = "Transactions.undefined.tx_id"

我对 N:M 的使用不正确吗?我在其他地方的“查找”查询中成功使用了“通过”构造,但是由于这个“通过”嵌套在包含中,它的行为似乎有所不同(例如要求我明确地通过.model)

任何帮助将不胜感激!

【问题讨论】:

    标签: sequelize.js


    【解决方案1】:

    复制TypeError: Cannot call method 'replace' of undefined

    您定义的 n:m 关系对我来说看起来不错。我已经在test script 中复制了 TypeError,您对through.where 的使用对我来说也很好(文档here)。这可能是 Sequelize 中的错误。

    解决您问题的方法

    查找用户 X 拥有的所有标签或与用户 X 关联 1 个以上事务的标签的一种方法是使用 2 次 findAll 调用,然后对结果进行重复数据删除:

    function using_two_findall(user_id) {
      var tags_associated_via_tx = models.tag.findAll({
        include: [{
          model: models.transaction,
          include: [{
            model: models.user,
            where: { id: user_id }
          }]
        }]
      });
    
      var tags_owned_by_user = models.tag.findAll({
        where: { owner_id: user_id }
      });
    
      return Promise.all([tags_associated_via_tx, tags_owned_by_user])
      .spread(function(tags_associated_via_tx, tags_owned_by_user) {
        // dedupe the two arrays of tags:
        return _.uniq(_.flatten(tags_associated_via_tx, tags_owned_by_user), 'id')
      });
    }
    

    另一种方法是使用您建议的原始查询:

    function using_raw_query(user_id) {
      var sql = 'select s05.tag.id, s05.tag.owner_id from s05.tag ' +
                'where s05.tag.owner_id = ' + user_id + ' ' +
                'union ' +
                'select s05.tag.id, s05.tag.owner_id from s05.tag, s05.transaction, s05.user_tx ' +
                'where s05.tag.id = s05.transaction.tag_id and s05.user_tx.tx_id = s05.transaction.id and ' +
                's05.user_tx.user_id = ' + user_id;
    
      return sq.query(sql, { type: sq.QueryTypes.SELECT})
      .then(function(data_array) {
        return _.map(data_array, function(data) {
          return models.tag.build(data, { isNewRecord: false });;
        });
      })
      .catch(function(err) {
        console.error(err);
        console.error(err.stack);
        return err;
      });
    }
    

    您可以在此答案中上面链接的测试脚本中看到这两种技术。

    作为一个快速说明,您可以看到我的原始查询与您的有点不同。当我运行你的时,它没有生成与问题描述相匹配的输出。另外,作为另一个快速说明,我的原始 SQL 查询使用联合。目前通过 find API 续集doesn't support them

    性能?

    仅查看生成的 SQL,原始查询将比对 findAll 的两次调用要快。另一方面,对 findAll 的两次调用更清晰,过早优化是愚蠢的。无论我使用哪种技术,我都会将其包装在 class method 中:)

    【讨论】:

    • 在这里提交了一个问题来续集github:github.com/sequelize/sequelize/issues/4866
    • 感谢您努力诊断问题,并通过在 Github 上发布问题进行跟进。我最终做了两个单独的 findAll 查询。使用 lodash 的重复数据删除功能的绝佳技巧。
    猜你喜欢
    • 2020-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-19
    • 1970-01-01
    • 1970-01-01
    • 2016-07-18
    • 1970-01-01
    相关资源
    最近更新 更多