Gajus Gajus - 3 months ago 10
Node.js Question

How to fetch only related data?

Assuming a simple one-to-many relationship, e.g.

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)
}
});


How do I fetch all posts of a specific blog entry without fetching the blog entry?

Using:

Blog
.where('id', args.id)
.fetch({
withRelated: [
Post
]
})
.call('related', 'post')
.call('toJSON');


causes an extranous request.

The only way I have found to do it is by querying
Post
object using a custom query, e.g.

Post
.where('blog_id', parent.id)
.fetchAll()
.call('toJSON');


The problem with the latter approach is that it negates the purpose of having the relations set in the first place.

JMM JMM
Answer

Use Model.forge() to instantiate an object with the primary-key. Then use model.load() to eager load attributes onto a Model, e.g.

Blog
  .forge({
    id: 1
  })
  .load('posts')
  .call('related', 'posts')
  .call('toJSON')
  .then((posts) => {
    console.log('posts', posts);
  });

Which produces:

posts [ { id: 1,
    blogId: 1,
    name: 'FOO',
    body: 'foo',
    imageUrl: null,
    createdAt: 2016-08-18T18:11:38.000Z,
    updatedAt: 2016-08-18T18:11:50.000Z },
  { id: 2,
    blogId: 1,
    name: 'BAR',
    body: 'bar',
    imageUrl: null,
    createdAt: 2016-08-18T18:11:43.000Z,
    updatedAt: 2016-08-18T18:11:52.000Z } ]