2

假设我收到的数据已经标准化,或者至少是关系。如何将这些数据插入到 vuex-orm 数据库中?

示例 JSON 数据:

{
  "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"
    }
  ]
}

制造商 Model 和 Carmodel 插入如下:

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

此示例模型将不起作用:

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')
    }
  }
}
4

1 回答 1

0

好的,我想我明白了。而不是this.hasOne ,我必须使用belongsTo并使用同一型号的manufacturer_id:

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')
    }
  }
}
于 2020-05-05T17:16:52.203 回答