简体   繁体   中英

How can I join three tables in Bookshelf.js?

I read the Bookshelf documentation related to through , but, but I can't found out how I should proceed. I have three tables named in a different convention than Bookshelf uses. Basically, a Group has many Users through Profile. The last one that makes the connection.

Table Name: User
   - id_user
   - username
   - password

Table Name: Profile
  - id_user
  - id_group

Table Name: Group
 - id_group
 - name
 - description
 - status

My group model is like so:

module.export = BookShelf.model('Group', {
  tableName: 'pats_grupos',

  users: function() {
    return this.hasMany('User').through('Profile');
  }
});

Taking in consideration that my tables don't follow the _id convention (but instead, the id_ one), how can I tell Bookshelf to work with my custom table naming pattern?

Accordingly to Bookshelf's idAttribute documentation , when not using the default 'id' you must change your models to explicitly declare the id attribute used. Like:

module.export = BookShelf.model('Group', {
  tableName: 'pats_grupos',
  idAttribute: 'id_group',

  users: function() {
    return this.hasMany('User').through('Profile');
  }
});

And since your foreign keys are also not following Bookshelf default naming you may have to declare them explicitly on the through() call too. Something like:

//...
users: function() {
  return this
    .hasMany('User')
    .through('Profile', 'id_user', 'id_group');
}
//...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM