私のアプリケーションのすべてのユーザー情報を含むユーザーモデルがあります。Sequelize.js - 別のモデルの2つのキーでモデルを関連付ける方法
// 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を持っています。セッションの各レコードには、セッション中にユーザーがペア設定されたユーザーIDと、ユーザーIDの両方の列があります。次のように私のセッションモデルは次のとおりです。
// 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;
};
私は(検索キーとしてユーザーIDを使用して)セッションからレコードを返します。クエリを記述しようとしていますが、またチームメイトの情報が含まれます。チームメイトの情報を含めることができるように(ユーザーモデルと結合されたセッションの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);
})
});