当通过映射程序急切地加载关系时,opts参数将传递到加载的关系。在我的例子中,这破坏了api。例如:
storyMapper.findAll({ title: 'foobar' }, { with: ['user'] });这导致两项请求:
GET /stories?title=foobar
GET /users?title=foobar我可能遗漏了一些东西,但我希望使用所定义的关系,以便先加载故事,然后是userId字段read,第二个查询类似于
GET /users/<the id>或者至少
GET /users?where=<id in <the id>>所以我的问题是:我是否可以改变这种行为,或者在每个故事加载之后是否需要对其使用loadRelations?
代码样本:
// user schema
import { Schema } from 'js-data';
export const user = new Schema({
$schema: 'http://json-schema.org/draft-04/schema#',
title: 'User',
description: 'Schema for User records',
type: 'object',
properties: {
_id: { type: 'string' },
username: { type: 'string' },
email: { type: 'string' },
password: { type: 'string' },
},
required: ['username', 'email', 'password'],
});// story schema
import { Schema } from 'js-data';
export const story = new Schema({
$schema: 'http://json-schema.org/draft-04/schema#',
title: 'Story',
description: 'Schema for Story records',
type: 'object',
properties: {
_id: { type: 'string' },
title: { type: 'string', default: '' },
userId: { type: ['string', 'null'] },
username: { type: ['string', 'null'] },
},
required: ['title'],
});// user mapper
this.store.defineMapper('user', {
mapperClass: ObservableMapper,
recordClass: User,
endpoint: 'users',
idAttribute: '_id',
schema: schemas.user,
relations: relations.user,
})// story mapper
this.store.defineMapper('story', {
mapperClass: ObservableMapper,
recordClass: Story,
endpoint: 'storys',
idAttribute: '_id',
schema: schemas.story,
relations: relations.story,
})// user relations
export const user = {
hasMany: {
world: {
foreignKey: 'userId',
localField: 'worlds',
},
},
};// story relations
export const world = {
belongsTo: {
user: {
foreignKey: 'userId',
localField: 'user',
},
},
};从GET /stories?title=foobar返回的样本数据
{
"_id": "546e53dcedee82d542000003",
"userId": "526e8617964fd22d2b000001",
"username": "Someone",
"title": "Lorem Ipsum"
}发布于 2017-01-29 22:01:41
你错过了用户故事关系的另一面:
// user relations
export const user = {
hasMany: {
story: {
foreignKey: 'userId',
localField: 'stories'
},
world: {
foreignKey: 'userId',
localField: 'worlds'
}
}
};现在,当您实际提出请求时,您有两个选项:
备选方案1-多个请求
这要求服务器理解"where“querystring参数:
store.findAll('story', { title: 'foobar' }, { with: ['user'] })下面是一个演示的柱塞:https://plnkr.co/edit/UCFJNg?p=preview
柱塞实例提出两个请求:
GET /stories?title=foobarGET /users?title=foobar&where={"_id":{"in":[123,234]}}备选方案2-单一请求
这要求服务器理解"with“querystring参数:
store.findAll('story', { title: 'foobar' }, { params: { with: ['user'] } })下面是一个演示的柱塞:https://plnkr.co/edit/M6quP4?p=preview
柱塞示例只发出一个请求,并期望用户嵌入服务器响应中的故事中:
GET /stories?with=user&title=foobar备注
这是HTTP适配器的一个怪癖。对于所有其他适配器,使用with选项会像您所期望的那样工作,您也不必使用params选项。
https://stackoverflow.com/questions/41243318
复制相似问题