sails.js和水线模型中的设计奇迹。
我有一个“熊”模型和一个“位置”模型。他们持有oneToMany协会(“熊可以随着时间的推移有多个位置”)。
bear.js
module.exports = {
attributes: {
location: {
collection: 'location',
via: 'bear'
}
}
};
location.js
module.exports = {
attributes: {
timestamp: {
type: 'datetime',
required: true
},
bear: {
model: 'bear'
}
}
};
我正试图让一个“oneToOne”协会抓住熊的最后位置(lastLocation
),并想知道什么是最好的解决方案:
find
)谢谢=)
答案 0 :(得分:1)
我认为这是你的答案?
创建一个真正的oneToOne关系并在位置添加一个钩子AfterCreate来更新那个“lastLocation”关联?
你应该在名为lastLocation:{model:'location'}
的熊上创建一个额外的属性,并在关联的熊上创建每个位置后自动更新。他们还可以做到这一点,但如果最后一个位置是经常阅读的东西,那么这可能是你最好的方法。
现在这是一个基于意见的一点点,因为你的设计中肯定会涉及很多因素,但我认为使用这种方法会很好。
答案 1 :(得分:0)
以下是我最终的结果:
model / Bear.js - 上次位置关联
lastLocation: {
model: 'location'
}
model / Location.js - afterCreate
hook
afterCreate: function(insertedLocation, callback) {
if(!insertedLocation.bear) {
return callback();
}
Bear.findOneById(insertedLocation.bear, function(err, bear) {
if(err) {
return callback(err);
}
Location.findOneById(bear.lastLocation, function(err, oldLastLocation) {
bear.lastLocation = insertedLocation.id;
bear.save(function(err) {
return callback(err);
});
});
});
}
if(!insertedLocation.bear)
测试是关键
我在afterUpdate
hook
afterUpdate: function(updatedLocation, callback) {
if(!updatedLocation.bear) {
return callback();
}
Bear.findOneById(updatedLocation.bear, function(err, bear) {
if(err) {
return callback(err);
}
Location.findOneById(bear.lastLocation, function(err, oldLastLocation) {
bear.lastLocation = updatedLocation.id;
bear.save(function(err) {
return callback(err);
});
});
});
}
添加测试以防止每次更新lastLocation时更新承担
PublishUpdate()
逻辑