Removing many-to-many relationship via update in Vuex-ORM

308 Views Asked by At

I'm wondering if it is possible to remove relationships between two models by simply updating a model on one side of the relationship. Adding new relationships just works fine but removing seems not to be an option but maybe I am just missing something. It seems logical that insertOrUpdate() does not "delete" nested relationship but maybe there is another function or property so set to get the desired behavior. Unfortunately, searching the docs was not successful.

In my case I configured a belongsToMany (m:n) relationship between model "Process" and model "Dependency". The m-n-model inbetween is "MapProcessDependency"

The Models

// Dependency.js
export default class Dependency extends Model {
  static entity = 'dependencies'
  static fields () {
    return {
      id: this.attr(null),
      name: this.string('')
    }
  }
}
// Process.js
export default class Process extends Model {
  static entity = 'processes'
  static fields () {
    return {
      id: this.attr(null),
      name: this.string(''),
      dependencies: this.belongsToMany(
        Dependency, MapProcessDependency, 'processId', 'dependencyId'
      )
    }
  }
}
// MapProcessDependency
export default class MapProcessDependency extends Model {
  static entity = 'mapProcessesDependencies'
  static primaryKey = ['processId', 'dependencyId']
  static fields () {
    return {
      processId: this.attr(null),
      dependencyId: this.attr(null)
    }
  }
}

The Vuex-ORM database

dependencies: [
  {
    "id": 1,
    "name": "Dep1",
    "$id": "1"
  },
  {
    "id": 2,
    "name": "Dep2",
    "$id": "2"
  }
],
processes: [
  {
    "id": 99,
    "name": "MyProc",
    "dependencies": [ /* managed via vuex-orm in mapProcessesDependencies */],
    "$id": "99"
  }
],
mapProcessesDependencies: [
  "[99,1]": {
    "processId": 99,
    "dependencyId": 1,
    "$id": "[99,1]"
  },
  "[99,2]": {
    "processId": 99,
    "dependencyId": 2,
    "$id": "[99,2]"
  }
]

What I want to achieve

// ...by calling this:
Process.insertOrUpdate({ where: 99, data: {
    "id": 99,
    "name": "MyProc",
    "dependencies": [ 1 ],
} })

...is the following result without manually calling MapProcessDependency.delete([99,2]):

// [...]
mapProcessesDependencies: [
  "[99,1]": {
    "processId": 99,
    "dependencyId": 1,
    "$id": "[99,1]"
  }
  // relationship [99,2] removed
]
0

There are 0 best solutions below