Vuex-ORM插入并合并两个相互关联的API调用
无法理解Vuex-ORM在我的特殊情况下的优势。
我有一个睡觉接口,大多数情况下我会设法使用多个接口调用来处理数据以显示结果。
例如:
通过调用fetchUsers()
和调用fetchPosts
,帖子由用户发出,并作为userId
道具在中关联。
用户数据
const users = [
{
id: 1,
name: 'Leanne Graham',
username: 'Bret',
email: 'Sincere@april.biz',
},
{
id: 2,
name: 'Ervin Howell',
username: 'Antonette',
email: 'Shanna@melissa.tv',
},
{
id: 3,
name: 'Clementine Bauch',
username: 'Samantha',
email: 'Nathan@yesenia.net',
},
{
id: 4,
PostData
const posts = [
{
userId: 1,
id: 1,
title:
'sunt aut facere repellat provident occaecati excepturi optio reprehenderit',
body:
'quia et suscipit
suscipit recusandae consequuntur expedita et cum
reprehenderit molestiae ut ut quas totam
nostrum rerum est autem sunt rem eveniet architecto',
},
{
userId: 2,
id: 2,
title: 'qui est esse',
body:
'est rerum tempore vitae
sequi sint nihil reprehenderit dolor beatae ea dolores neque
fugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis
qui aperiam non debitis possimus qui neque nisi nulla',
},
{
userId: 3,
id: 3,
title: 'ea molestias quasi exercitationem repellat qui ipsa sit aut',
body:
'et iusto sed quo iure
voluptatem occaecati omnis eligendi aut ad
voluptatem doloribus vel accusantium quis pariatur
molestiae porro eius odio et labore et velit aut',
},
{
userId: 3,
id: 4,
title: 'eum et est occaecati',
body:
'ullam et saepe reiciendis voluptatem adipisci
sit amet autem assumenda provident rerum culpa
quis hic commodi nesciunt rem tenetur doloremque ipsam iure
quis sunt voluptatem rerum illo velit',
},
{
userId: 5,
id: 5,
title: 'nesciunt quas odio',
body:
'repudiandae veniam quaerat sunt sed
alias aut fugiat sit autem sed est
voluptatem omnis possimus esse voluptatibus quis
est aut tenetur dolor neque',
},
]
将此作为Prepare,我将在我的存储操作中调用这两个API的异步。
import Vue from 'vue'
import Vuex from 'vuex'
// import mock api data
import usersData from '@/data/users'
import postsData from '@/data/posts'
// import to VUEX-ORM Database
import User from '@/store/models/User'
import Post from '@/store/models/Post'
import VuexORM from '@vuex-orm/core'
Vue.use(Vuex)
const database = new VuexORM.Database()
database.register(User)
database.register(Post)
export default new Vuex.Store({
plugins: [VuexORM.install(database)],
getters: {
users: () => {
return User.all()
},
posts: () => {
return Post.all()
},
},
actions: {
async fetchUsers() {
const fetchingUsers = await new Promise((resolve, reject) => {
return setInterval(() => {
resolve(usersData)
reject(
'Issue on fetching, but usually this is not possible in a mock'
)
}, 300)
})
User.insert({ data: fetchingUsers })
},
async fetchPosts() {
const fetchingPosts = await new Promise((resolve, reject) => {
return setInterval(() => {
resolve(postsData)
reject(
'Issue on fetching, but usually this is not possible in a mock'
)
}, 300)
})
Post.insert({ data: fetchingPosts })
},
deleteUser(context, userId) {
User.delete((user) => user.id === userId)
},
addUser(context, userData) {
userData.id = User.all().length + 1
User.insertOrUpdate({ data: userData })
},
},
modules: {},
})
我现在想要的就是帖子应该放到相关用户那里 我的模型定义如下:
用户模型
import { Model } from '@vuex-orm/core'
import Post from './Post'
export default class User extends Model {
static entity = 'user'
static fields() {
return {
id: this.attr(null),
name: this.attr(''),
username: this.attr(''),
email: this.attr(''),
posts: this.hasMany(Post, 'userId')
}
}
}
开机自检模型
import { Model } from '@vuex-orm/core'
import User from './User'
export default class Post extends Model {
static entity = 'post'
static fields() {
return {
id: this.attr(null),
userId: this.belongsTo(User, 'id'),
title: this.attr(''),
body: this.attr(''),
}
}
}
最大的问题是,为什么我的帖子没有进入我的Users对象,这样我就可以用他们属于的帖子来显示用户。我的用户中的帖子数组是空的。有人知道为什么吗?
解决方案
您在VUE-DevTools中看到的内容是预期的。
关系不会插入到存储区中,它们会插入到各自的";表";中,并为其分配外键以创建对该关系的引用。
当您查询实体以包括关系时,即User.query().with('posts').get()
,您会注意到帖子将被填充。但是,存储中的关系字段将始终显示为空数组(对于许多关系)或NULL(对于单个关系),因为这只是实体的架构。
相关文章