当急切地通过映射器加载关系时,opts
参数将传递给加载的关系。这打破了我的情况下的api。例如:
storyMapper.findAll({ title: 'foobar' }, { with: ['user'] });
这导致两个请求:
GET /stories?title=foobar
GET /users?title=foobar
我可能会遗漏某些内容,但我希望使用已定义的关系,以便首先加载故事,将userId
字段读取,然后将第二个查询添加为
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"
}
答案 0 :(得分:1)
您错过了用户 - 故事关系的另一面:
// user relations
export const user = {
hasMany: {
story: {
foreignKey: 'userId',
localField: 'stories'
},
world: {
foreignKey: 'userId',
localField: 'worlds'
}
}
};
现在,当您实际提出请求时,您有两个选择:
这要求您的服务器理解&#34;其中&#34;查询字符串参数:
store.findAll('story', { title: 'foobar' }, { with: ['user'] })
这是一名演员:https://plnkr.co/edit/UCFJNg?p=preview
plunker示例提出了两个请求:
GET /stories?title=foobar
GET /users?title=foobar&where={"_id":{"in":[123,234]}}
这要求您的服务器理解&#34;&#34;查询字符串参数:
store.findAll('story', { title: 'foobar' }, { params: { with: ['user'] } })
这是一名演员:https://plnkr.co/edit/M6quP4?p=preview
plunker示例只生成一个请求,并期望用户嵌入到服务器响应中的故事中:
GET /stories?with=user&title=foobar
这是HTTP适配器的一个怪癖。对于所有其他适配器,使用with
选项可以按照您的预期运行,并且您不必使用params
选项。