vue.jsvuexvuex-orm

Inserting data in vuex-orm database that is already normalized


Assuming the data i receive is already normalized, or at least the relations. How can this data be inserted into the vuex-orm database?

Example JSON data:

{
  "carmodel": [
    {
      "id": 1,
      "title": "M3",
      "manufacturer_id": 1
    },
    {
      "id": 2,
      "title": "a-class"
      "manufacturer_id": 2
    }
  ],
  "manufacturer": [
    {
      "id": 1,
      "title": "BMW"
    },
    {
      "id": 2,
      "title": "Mercedes"
    }
  ]
}

Manufacturer Model and Carmodel are inserted like this:

Manufacturer.insert({ data: response.data.manufacturer })
CarModel.insert({ data: response.data.carmodel })

This example model will not work:

import { Model } from '@vuex-orm/core'
import Manufacturer from '@/models/Manufacturer'

export default class CarModel extends Model {
  static entity = 'carModels'

  static fields () {
    return {
      id: this.attr(null),
      title: this.string(''),
      manufacturer: this.hasOne(Manufacturer, 'manufacturer_id')
    }
  }
}

Solution

  • Ok, i think i got it. Instead of this.hasOne i have to use belongsTo and use the manufacturer_id from the same model:

    import { Model } from '@vuex-orm/core'
    import Manufacturer from '@/models/Manufacturer'
    
    export default class CarModel extends Model {
      static entity = 'carModels'
    
      static fields () {
        return {
          id: this.attr(null),
          title: this.string(''),
          manufacturer_id: this.attr(null),
          manufacturer: this.belongsTo(Manufacturer, 'manufacturer_id')
        }
      }
    }