如何在Bookshelf.js中加入三张表格?
问题描述:
我阅读了与through
相关的书架文档,但是我找不到应该如何继续。我有三个以与Bookshelf不同的约定命名的表。基本上,一个集团有许多用户通过配置文件。最后一个建立连接。如何在Bookshelf.js中加入三张表格?
Table Name: User
- id_user
- username
- password
Table Name: Profile
- id_user
- id_group
Table Name: Group
- id_group
- name
- description
- status
我的小组模式是像这样:
module.export = BookShelf.model('Group', {
tableName: 'pats_grupos',
users: function() {
return this.hasMany('User').through('Profile');
}
});
也要考虑到我的表不按约定_id
(但相反,id_
之一),我怎么能告诉书架工作用我的自定义表命名模式?
答
根据Bookshelf's idAttribute
documentation,如果不使用默认的“id”,则必须更改模型以显式声明使用的id属性。像:
module.export = BookShelf.model('Group', {
tableName: 'pats_grupos',
idAttribute: 'id_group',
users: function() {
return this.hasMany('User').through('Profile');
}
});
而且因为你的外键,也没有遵循书架默认命名你可能必须明确声明他们的through()
call了。例如:
//...
users: function() {
return this
.hasMany('User')
.through('Profile', 'id_user', 'id_group');
}
//...