【发布时间】:2014-09-09 20:23:56
【问题描述】:
我的 Sailsjs 应用程序中有以下具有多对多关系的模型:
event.js:
attributes: {
title : { type: 'string', required: true },
description : { type: 'string', required: true },
location : { type: 'string', required: true },
maxMembers : { type: 'integer', required: true },
currentMembers : { collection: 'user', via: 'eventsAttending', dominant: true },
creator : { model: 'user', required: true },
invitations : { collection: 'invitation', via: 'eventID' },
tags : { collection: 'tag', via: 'taggedEvents', dominant: true },
lat : { type: 'float' },
lon : { type: 'float' },
},
tags.js:
attributes: {
tagName : { type: 'string', unique: true, required: true },
taggedEvents : { collection: 'event', via: 'tags' },
},
根据文档,这种关系看起来是正确的。我在 tag.js 中有以下方法,它接受一个标签字符串数组和一个事件 id,并且应该添加或删除传入的标签:
modifyTags: function (tags, eventId) {
var tagRecords = [];
_.forEach(tags, function(tag) {
Tag.findOrCreate({tagName: tag}, {tagName: tag}, function (error, result) {
tagRecords.push({id: result.id})
})
})
Event.findOneById(eventId).populate('tags').exec(function(error, event){
console.log(event)
var currentTags = event.tags;
console.log(currentTags)
delete currentTags.add;
delete currentTags.remove;
if (currentTags.length > 0) {
currentTags = _.pluck(currentTags, 'id');
}
var modifiedTags = _.pluck(tagRecords, 'id');
var tagsToAdd = _.difference(modifiedTags, currentTags);
var tagsToRemove = _.difference(currentTags, modifiedTags);
console.log('current', currentTags)
console.log('remove', tagsToRemove)
console.log('add', tagsToAdd)
if (tagsToAdd.length > 0) {
_.forEach(tagsToAdd, function (tag) {
event.tags.add(tag);
})
event.save(console.log)
}
if (tagsToRemove.length > 0) {
_.forEach(tagsToRemove, function (tagId) {
event.tags.remove(tagId)
})
event.save()
}
})
}
这是从事件模型中调用方法的方式:
afterCreate: function(record, next) {
Tag.modifyTags(tags, record.id)
next();
}
当我发布到事件/创建时,我得到这个结果:http://pastebin.com/PMiqBbfR。
看起来好像方法调用本身是循环的,而不仅仅是 tagsToAdd 或 tagsToRemove 数组。更令人困惑的是,最后,在事件的最后一个日志中,看起来该事件具有正确的标签。但是,当我随后发布到 event/1 时,标签数组为空。我也尝试在每个.add() 之后立即保存,但仍然得到类似的结果。
理想情况下,我想循环遍历 tagsToAdd 和 tagsToRemove 数组,在模型集合中修改它们的 id,然后在模型上调用一次 .save()。
我花了很多时间尝试调试它,所以任何帮助都将不胜感激!
【问题讨论】:
标签: javascript sails.js waterline