在我的应用程序中,我有用户和联系人。用户向其他用户发出ContactRequests。 ContactRequest有一个请求者和被请求者字段。我不知道怎么回事。我不想要Users,ContactRequests和ContactRequestsUsers表(如果我在Users和ContactRequests上定义了hasMany或hasOne,则会为sequelize。)
让我先来定义一些模型 -
var User = sequelize.define('User', {
id: {type: seq.INTEGER, primaryKey: true, autoIncrement: true},
username: {
type: sequelize.STRING(32)
}
});
var ContactRequest = sequelize.define('ContactRequest', {
id: {type: seq.INTEGER, primaryKey: true, autoIncrement: true}
});
不确定我应该做什么关联。似乎我应该能够通过几种方式(理论上)做到这一点,但我无法通过任何方式尝试工作。
// User Has Many?
User.hasMany(ContactRequest, {as: 'Requester', foreignKey: 'requester'});
User.hasMany(ContactRequest, {as: 'Requestee', foreignKey: 'requestee'});
// ContactRequest Belongs to?
ContactRequest.belongsTo(User, {});
// Experience Has One?
ContactRequest.hasOne(User, {as: 'Requester'});
ContactRequest.hasOne(User, {as: 'Requestee'});
对于每个变体,我尝试了不同的方法来检查userA是否向userB发出了ContactRequest。
// Checking if a user has a contact request?
var userA = 'someuser1';
var userB = 'someuser2';
ContactRequest.find({where: {'Requester.username': userA, 'Requestee.username': userB}, include: [{model: User, as: 'Requester'}, {model: User, as: 'Requestee'}]}).success(function(cr) {
console.log(cr);
});
// Maybe by the user?
User.find({where: {username: userA}}).success(function(someuser) {
someuser.getRequestee({where: {'Requestee.username': userB}, include: [{model: User, as: 'Requestee'}]}).success(function(cr) {
console.log(cr);
});
});
不确定我哪里出错但我不能让它发挥作用。任何帮助或远见将不胜感激。