如何只获取相关数据?
How to fetch only related data?
假设一个简单的一对多关系,例如
const Blog = Bookshelf.Model.extend({
tableName: 'blog',
posts: function () {
return this.hasMany(Post);
}
});
const Post = Bookshelf.Model.extend({
tableName: 'post',
blog: function () {
return this.belongsTo(Blog)
}
});
如何在不获取博客条目的情况下获取特定博客条目的所有帖子?
使用:
Blog
.where('id', args.id)
.fetch({
withRelated: [
Post
]
})
.call('related', 'post')
.call('toJSON');
导致一个额外的请求。
我找到的唯一方法是使用自定义查询查询 Post
对象,例如
Post
.where('blog_id', parent.id)
.fetchAll()
.call('toJSON');
后一种方法的问题在于它否定了首先设置关系的目的。
实例化一个模型(你可以使用new Model
或Model.forge()
) and set the primary key (however you want, but passing it in initial attributes is usually easiest). Then call model.load()
来预先加载相关模型。示例:
Blog
.forge({
id: 1
})
.load('posts')
.call('related', 'posts')
.call('toJSON')
.then((posts) => {
console.log('posts', posts);
});
假设一个简单的一对多关系,例如
const Blog = Bookshelf.Model.extend({
tableName: 'blog',
posts: function () {
return this.hasMany(Post);
}
});
const Post = Bookshelf.Model.extend({
tableName: 'post',
blog: function () {
return this.belongsTo(Blog)
}
});
如何在不获取博客条目的情况下获取特定博客条目的所有帖子?
使用:
Blog
.where('id', args.id)
.fetch({
withRelated: [
Post
]
})
.call('related', 'post')
.call('toJSON');
导致一个额外的请求。
我找到的唯一方法是使用自定义查询查询 Post
对象,例如
Post
.where('blog_id', parent.id)
.fetchAll()
.call('toJSON');
后一种方法的问题在于它否定了首先设置关系的目的。
实例化一个模型(你可以使用new Model
或Model.forge()
) and set the primary key (however you want, but passing it in initial attributes is usually easiest). Then call model.load()
来预先加载相关模型。示例:
Blog
.forge({
id: 1
})
.load('posts')
.call('related', 'posts')
.call('toJSON')
.then((posts) => {
console.log('posts', posts);
});