Gajus
Gajus

Reputation: 73848

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.

Upvotes: 0

Views: 214

Answers (1)

JMM
JMM

Reputation: 26807

Instantiate a model (you can use new Model or Model.forge()) and set the primary key (however you want, but passing it in initial attributes is usually easiest). Then call model.load() to eager load the related models. Example:

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

Upvotes: 1

Related Questions