1

How do i achieve the following relation in bookshelf.js

SELECT user_accounts.user_id,  `event_id` 
FROM  `calendar_events` 
JOIN user_accounts ON user_accounts.user_id = calendar_events.`created_by` 
LIMIT 10

My Model

var CalendarEvent = bookshelf.Model.extend({
    tableName: 'calendar_events',
    hasTimestamps: ['created_on'],
    user: function() {
        return this.hasOne('UserAccount','user_id');
    }
});

var UserAccount = bookshelf.Model.extend({
    tableName: 'user_account'
});

2 Answers 2

3

If you wanted to get that exact style query, you could use the knex query builder and try to build a query to match your needs

have not tested this but should be something like this

CalendarEvent.forge().query(function(qb){
  qb.join('user_accounts', 'user_accounts.user_id', '=', 'calendar_events.created_by');
  //qb.where() //if you wanted
  //qb.andWhere();  //and if you wanted more
  qb.limit(10);

})    
.fetchAll();

(you dont need the .where or .andWhere, just added those for fun)

It might be possible to do it purely in bookshelf, but i'm not sure of how at the moment.

0

I suppose you found the solution since 2016 but here is the answer

var CalendarEvent = bookshelf.Model.extend({
    tableName: 'calendar_events',
    hasTimestamps: ['created_on'],
    user: function() {
        return this.belongsTo(UserAccount, 'user_id', 'created_by');
    }
});

var UserAccount = bookshelf.Model.extend({
    tableName: 'user_account'
});

Use belongsTo() method because the foreign key is in the CalendarEvent Model and not in the UserAccount model. Append the name of the foreign key to belongsTo() parameters to specify the name of the foreign key.

Then, use the Bookshelf model like this :

CalendarEvent
    .forge()
    .fetchPage({ pageSize: 10, withRelated: ['user'] })
    .then(data => {
        // Data retrieval
    })
    .catch(exc => {
        // Error management
    });

The fetchPage method uses page and pageSize to create a pagination. You will retrieve a data.pagination object containing rows info (number to rows, page number, page size, page total count) and data.toJSON() will retrieve your models.

2
  • 2
    This does not do a single join query. It makes two sql queries, one to fetch CalendarEvent and another for UserAccount.
    – squgeim
    Apr 19, 2018 at 6:48
  • That's true but that's not the question. OP wanted to know how to achieve his query using Bookshelf, I'm giving the answer. One or multiple queries is not the question.
    – Eric Ly
    Apr 19, 2018 at 8:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.