我正在使用 3.0.0-rc.4 的 js-data,我需要通过对后端 API 的一次调用加载多个模型。我仍在构建后端,并且希望能够一次从不同的表中检索所有数据,而不是对不同的端点进行多次调用。
最佳答案
可以。假设您的 Web 应用程序尝试加载的路径是/posts/123,您需要加载 Post #123 及其评论,它们位于两个不同的表中。在您的客户端应用程序中,您可以执行以下操作
store.find('post', 123)
甚至
store.find('post', 123, { params: { with: 'comment' } })
这将分别向 /post/123
和 /post/123?with=comment
发出 GET 请求。
您的后端可以使用嵌入了 Comments 的 Post 记录进行响应,只要您告诉 JSData 关于帖子和评论之间的关系,它们就会被缓存到内存存储的正确部分。例如:
store.defineMapper('post', {
relations: {
hasMany: {
comment: {
localField: 'comments',
foreignKey: 'post_id'
}
}
}
});
store.defineMapper('comment', {
relations: {
belongsTo: {
post: {
localField: 'post',
foreignKey: 'post_id'
}
}
}
});
你这样做:
store.find('post', 123)
您的后端响应:
{
"id": 123,
// ...
}
你这样做:
store.find('post', 123, { params: { with: 'comment' } })
您的后端响应:
{
"id": 123,
// ...,
comments: [
{
"id": 14323,
"post_id": 123,
// ...
},
// ...
]
}
如果您在后端使用 Node.js + JSData,请查看 https://github.com/js-data/js-data-express它可以正确解析查询字符串并为所有 Mappers 生成所有 Express 路由。使用 js-data-express,您的后端将能够完全按照我在上面的示例中指出的那样响应请求。
一旦您将数据加载到内存存储中,您的 View 组件就可以从内存存储中提取它需要显示的数据:
从内存存储中获取帖子#123:
store.get('post', 123)
从内存存储中获取帖子 #123 的评论:
store.getAll('comment', 123, { index: 'post_id' })
如果您正在使用 DataStore
组件,那么帖子的评论也应该在帖子记录本身上可用,例如post.comments
.
关于javascript - 单个路由中的 js-data 多个模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39986760/