ManyToManyUpdateOperationBase.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. const UpdateOperation = require('../../../queryBuilder/operations/UpdateOperation');
  2. class ManyToManyUpdateOperationBase extends UpdateOperation {
  3. constructor(name, opt) {
  4. super(name, opt);
  5. this.relation = opt.relation;
  6. this.owner = opt.owner;
  7. this.hasExtraProps = false;
  8. this.joinTablePatch = {};
  9. this.joinTablePatchFilterQuery = null;
  10. }
  11. onAdd(builder, args) {
  12. const modelClass = builder.modelClass();
  13. const obj = args[0];
  14. // Copy all extra properties to the `joinTablePatch` object.
  15. for (let i = 0; i < this.relation.joinTableExtras.length; ++i) {
  16. const extra = this.relation.joinTableExtras[i];
  17. if (extra.aliasProp in obj) {
  18. this.hasExtraProps = true;
  19. this.joinTablePatch[extra.joinTableProp] = obj[extra.aliasProp];
  20. }
  21. }
  22. const res = super.onAdd(builder, args);
  23. if (this.hasExtraProps) {
  24. // Make sure we don't try to insert the extra properties
  25. // to the target table.
  26. this.relation.omitExtraProps([this.model]);
  27. }
  28. return res;
  29. }
  30. onBefore3(builder) {
  31. const row = this.model.$toDatabaseJson(builder.knex());
  32. if (Object.keys(row).length === 0) {
  33. // Resolve the main query if there is nothing to update. We still
  34. // need to continue executing this query since we may have `extra`
  35. // properties to update in `onAfter1`.
  36. builder.resolve([0]);
  37. }
  38. return super.onBefore3(builder);
  39. }
  40. onAfter1(builder, result) {
  41. if (this.hasExtraProps) {
  42. const joinTableUpdateQuery = this.relation
  43. .getJoinModelClass(builder.knex())
  44. .query()
  45. .childQueryOf(builder)
  46. .patch(this.joinTablePatch);
  47. return this.applyModifyFilterForJoinTable(joinTableUpdateQuery).return(result);
  48. } else {
  49. return result;
  50. }
  51. }
  52. /* istanbul ignore next */
  53. applyModifyFilterForRelatedTable(builder) {
  54. throw new Error('not implemented');
  55. }
  56. /* istanbul ignore next */
  57. applyModifyFilterForJoinTable(builder) {
  58. throw new Error('not implemented');
  59. }
  60. }
  61. module.exports = ManyToManyUpdateOperationBase;