SailsJS 在创建具有关联的对象时触发更新

SailsJS Triggers Update when Creating Object with Associations

本文关键字:对象 更新 关联 创建 SailsJS      更新时间:2023-09-26

我正在使用 Sails v0.10.5。

我创建了三个模型,它们之间有关联。评估人员通过Candidate模型、Evaluator模型和Rating模型对候选人进行评分。我正在使用水线关联来自动跟踪从RatingEvaluatorCandidate的外键。

我还使用蓝图自动处理这些模型的所有CRUD路由。

不幸的是,每当我通过http://localhost:1337/rating/create?rating=4&comment=Great&evaluator=3&candidate=2蓝图创建一个新的候选者,除了触发预期的 CREATE,除了触发预期的 CREATE,sails 还会返回并调用 2 个 UPDATE,在此期间CandidateEvaluator的外键都被设置

这在我的应用程序的前端导致问题,因为它接收 UPDATE 事件而不是 CREATE 事件,并且没有必要的上下文来正确处理来自服务器的新数据。

任何解决此问题的建议都会有所帮助!

以下是水线模型:

/api/models/Candidate.js

module.exports = {
  schema: true,
  attributes: {
    name: {
      type: 'string',
      required: true
    },
    status: {
      type: 'string',
      required: true
    },
    role: {
      type: 'string',
      required: true
    },
    ratings: {
      collection: 'rating',
      via: 'candidate'
    }
  }
};

/api/models/Evaluator.js

module.exports = {
  schema: true,
  attributes: {
    name: {
      type: 'string',
      required: true
    },
    title: {
      type: 'string',
      required: true
    },
    role: {
      type: 'string',
      required: true
    },
    ratings: {
      collection: 'rating',
      via: 'evaluator'
    }
  }
};

/api/models/Rating.js

module.exports = {
  schema: true,
  attributes: {
    rating: {
      type: 'integer',
      required: true
    },
    comment: {
      type: 'string',
      required: false
    },
    evaluator: {
      model: 'evaluator',
      required: true
    },
    candidate: {
      model: 'candidate',
      required: true
    }
  }
};

我遇到了类似的问题。您可以在更新事件中创建筛选器,以检查并查看某些变量是否已更新,如果是,请调用一些影响前端的函数。

您可以覆盖Rating模型的publishCreate。 默认 publishCreate 方法中的大多数代码都致力于确定要通知哪些关联有关新模型以及如何通知它们;由于这正是您想要的,因此您在models/Rating.js中的方法可能非常简单:

publishCreate: function (values, req) {
  // Get all of the "watchers" of the Rating model
  var watchers = Rating.watchers();
  // Remove the socket responsible for the creation, if you don't want
  // it to get the "create" message too
  watchers = _.without(watchers, req.socket);
  // Send a message to the sockets with the "rating" event and the payload
  // expected for the "publishCreate" message
  sails.socket.emit(sockets, "rating", {
      verb: 'created',
      data: values,
      id: values[this.primaryKey]
  });
  // Subscribe all watchers to the new instance, if you're into that
  this.introduce(values[this.primaryKey]);
}

请注意,publishCreate 是模型的方法,因此它位于attributes对象之外