当通过映射器急切地加载关系时,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"
}