Skip to content

Instantly share code, notes, and snippets.

@kevinansfield
Created June 24, 2015 10:19
Show Gist options
  • Select an option

  • Save kevinansfield/d429317443355aa8b764 to your computer and use it in GitHub Desktop.

Select an option

Save kevinansfield/d429317443355aa8b764 to your computer and use it in GitHub Desktop.
bookshelf.js - Selecting certain columns from associations
// Select specified columns on relations when fetching:
new models.Post({id:1}).fetch({
withRelated: [{'tags': function(qb) { qb.column('tags.id') }}]
}).then(function(post) {
return post.related('tags').toJSON()
})
=> [ { id: 1, parent: undefined } ]
// knex querybuilder debug:
{ method: 'select',
options: undefined,
bindings: [ 'permalinks', 1 ],
sql: 'select "settings".* from "settings" where "settings"."key" = ? limit ?',
__cid: '__cid13' }
{ method: 'select',
options: undefined,
bindings: [ 1, 1 ],
sql: 'select "posts".* from "posts" where "posts"."id" = ? limit ?',
__cid: '__cid13' }
{ method: 'select',
options: undefined,
bindings: [ 1 ],
sql: 'select "tags"."id", "posts_tags"."post_id" as "_pivot_post_id", "posts_tags"."tag_id" as "_pivot_tag_id" from "tags" inner join "posts_tags" on "posts_tags"."tag_id" = "tags"."id" where "posts_tags"."post_id" in (?)',
__cid: '__cid13' }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment