【问题标题】:Sequelize two associate tables by an intermediate third table通过中间的第三个表对两个关联表进行排序
【发布时间】:2016-10-27 17:26:39
【问题描述】:

所以,我终于在我的 sequelize 代码中使用了关联。或者我是这么想的。

我有表 A 关联到表 B 和表 B 关联到表 C 通过外键。我想使用 A、B 和 C 中的过滤器从 A 中获取行。如果 C 不在图片中,我会这样做:

 models.A.findOne({
            attributes: ['id', 'col1', 'col2'],
            where: {
                  col1: value1, 
                  col3: value3
            }, 
            include: [{model: models.B, required: true}]
        }).then(function (result) {
            res.send(result);
        }).catch(function(error){
            console.log(error);
            res.send(error);
        });    

注意 col3 是表 B 中的一个字段。

现在我想做的最好写成:

 models.A.findOne({
            attributes: ['id', 'col1', 'col2'],
            where: {
                  col1: value1, 
                  col3: value3,
                  col5: value5
            }, 
            include: [{model: models.B, required: true}, {model: models.C, required: true}]
        }).then(function (result) {
            res.send(result);
        }).catch(function(error){
            console.log(error);
            res.send(error);
        });   

Col5 是表 C 的一个字段。

这样做(正确地)给我一个错误:C 未连接到 A。 我知道 A 连接到 B 和 B 连接到 C,因为我在模型中定义了这些连接。但我什至无法定义跨表关联——比如 A 和 C。

首先,我不知道该怎么做,其次,关联可能包含多达 5 个表的链。当我说链时,我指的是一系列关联,而不是同一张表的并行关联。

sequelize 如何处理这种情况?

【问题讨论】:

    标签: node.js associations sequelize.js model-associations


    【解决方案1】:

    好吧,那太丢人了。

    我想通了。符号如下:

     models.A.findOne({
                attributes: ['id', 'col1', 'col2'],
                where: {
                      col1: value1, 
                      col3: value3,
                      col5: value5
                }, 
                include: [{model: models.B, required: true}, include:[{model: models.C, required: true}]]
            }).then(function (result) {
                res.send(result);
            }).catch(function(error){
                console.log(error);
                res.send(error);
            });  
    

    基本上,嵌套关联的编写方式与 sequelize -nested 中的一样。

    感谢此来源http://lorenstewart.me/2016/09/12/sequelize-table-associations-joins/ 的彻底和简单的解释。

    【讨论】:

      猜你喜欢
      • 2014-02-14
      • 1970-01-01
      • 2016-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-05
      • 2014-07-27
      • 1970-01-01
      相关资源
      最近更新 更多