Sequelize.js - 如何通过另一个模型中的两个键关联模型

时间:2017-02-02 01:08:55

标签: javascript node.js associations sequelize.js

我有一个Users模型,其中包含我的应用程序的所有用户信息。

// model for the users table
module.exports = function(sequelize, DataTypes) {
    var User = sequelize.define("User", {
        email: {
            type: DataTypes.STRING,
            allowNull: false
        },
        password: {
            type: DataTypes.STRING,
            allowNull: false
        },
        displayName: {
            type: DataTypes.STRING
        },
        firstName: {
            type: DataTypes.STRING
        },
        lastName: {
            type: DataTypes.STRING
        }

    }, {
        classMethods: {
            associate: function(models) {
                User.hasMany(models.Session);  // adds key to Sessions for UserID
                User.hasMany(models.Session, {as: "TeammateId"});  // adds key to Sessions as 
            },
        }
    });
    return User;
};

该应用程序处理与队友完成任务。我有另一个模型Sessions,它跟踪每次尝试完成任务的数据。在Sessions中的每个记录中,我将UserID作为列以及TeammateID用于在会话期间用户与之配对的任何人。我的会话模型如下:

// model for the sessions table
module.exports = function(sequelize, DataTypes) {
    var Session = sequelize.define("Session", {
        success: {
            type: DataTypes.BOOLEAN,
            allowNull: false,
            default: false
        },
        TeammateId: {
            type: DataTypes.INTEGER,
            allowNull: false
        }
    }, {
        classMethods: {
            associate: function(models) {
                Session.belongsTo(models.User, { 
                    onDelete: "cascade",
                    foreignKey: {
                        allowNull: false
                    }
                });
            }
        }
    });
    return Session;
};

我正在尝试编写一个将从Sessions返回记录的查询(使用UserID作为查找键),但也会包含队友的信息。如何设置/修复我的关联,以便我可以包含队友的信息(使用与用户模型一起加入的Sessions中的TeammateID)?

我尝试的查询如下:

app.get("[omitted]", function(req, res){
    var userId = req.params.userId;
    db.Session.findAll({
      where: {
        UserId: userId
      },
      include: [db.User]  // this is where i am lost.  it only returns info for the User and not the Teammate
    }).then(function(data){
      res.json(data);
    })
  });

1 个答案:

答案 0 :(得分:0)

我找到了答案。关键不在于我如何必然地建立关联,而是在书面查询中包括'包括'一部分。这是我的工作代码:

用户模型:

// model for the users table
module.exports = function(sequelize, DataTypes) {
    var User = sequelize.define("User", {
        email: {
            type: DataTypes.STRING,
            allowNull: false
        },
        password: {
            type: DataTypes.STRING,
            allowNull: false
        },
        displayName: {
            type: DataTypes.STRING
        },
        firstName: {
            type: DataTypes.STRING
        },
        lastName: {
            type: DataTypes.STRING
        }

    }, {
        classMethods: {
            associate: function(models) {
                User.hasMany(models.Session);
                User.hasMany(models.Session, {
                    as: "Teammate"
                }); 
            },
        }
    });
    return User;
};

会话模型:

// model for the Sessions table
module.exports = function(sequelize, DataTypes) {
    var Session = sequelize.define("Session", {
        success: {
            type: DataTypes.BOOLEAN,
            allowNull: false,
            default: false
        }
    }, {
        classMethods: {
            associate: function(models) {
                Session.belongsTo(models.User, { 
                    as: "User",
                    onDelete: "cascade",
                    foreignKey: {
                        allowNull: false
                    }
                });
                Session.belongsTo(models.User, { 
                    as: "Teammate",
                    onDelete: "cascade",
                    foreignKey: {
                        allowNull: false
                    }
                });
            }
        }
    });
    return Session;
};

查询:

// route for returning session history with user and teammate information 
app.get("[ommitted]", function(req, res){
  var userId = req.params.userId;
  db.Session.findAll({
    where: {
      UserId: userId
    },
    include: [{
      model: db.User,
      as: "User"
    }, {
      model: db.User,
      as: "Teammate"
    }]
  }).then(function(data){
    // to do: parse the results into a summary easily consumed by the front end.
    res.send(data);
  })
});