我正在尝试构建一个tinder克隆应用程序,其中有两种不同类型的用户:player
和trainer
,他们可以一起匹配。我遍历了文档,试图找出在matches
表和messages
表之间实现的正确关联,其中匹配记录具有playerId和trainerId,消息也是如此。
我的问题是:
我该如何实现它,以及何时应用belongsTo,hasMany,belongsToMany关联?
这是我到目前为止所做的:
players.model.js
players.associate = function (models) {
players.hasMany(models.messages);
players.hasMany(models.matches);
};
trainers.model.js
teachers.associate = function (models) {
trainers.hasMany(models.messages);
trainers.hasMany(models.matches);
};
messages.model.js
messages.associate = function (models) {
messages.belongsTo(models.players);
messages.belongsTo(models.trainers);
messages.belongsTo(models.matches);
};
matches.model.js
matches.associate = function (models) {
matches.belongsTo(models.players);
matches.belongsTo(models.trainers);
matches.hasMany(models.messages);
};
您可以注册所有模型,之后所有它们的关联都像这样:
var fs = require('fs')
var path = require('path')
var basename = path.basename(module.filename)
var db = {}
var models = path.join(__dirname, 'models')
fs.readdirSync(models)
.filter(function(file) {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js')
})
.forEach(function(file) {
var model = sequelize['import'](path.join(models, file))
db[model.name] = model
})
Object.keys(db).forEach(function(modelName) {
if (db[modelName].associate) {
db[modelName].associate(db)
}
})
然后您可以导出db
对象以使用所有模型来查询数据
例如,与一位教练一起进行所有比赛,而一名球员包括为对象:
const allMatches = db.matches.findAll({
include: [db.trainers, db.players]
})