I'm fighting hard with relations inside my bookshelf model. What I'm trying to do is to create schema which contains 4 tables:
With relations between them like this:
users manyTOone roles manyTOone privileges_roles oneTOmany privileges
I've easily achieved relations between privileges and roles with:
Privileges
class Privileges {
constructor() {
this.model = bookshelf.Model.extend({
tableName: 'privileges',
roles: function () {
return this.belongsToMany(Roles.model).through(PrivilegeRole.model);
}
});
};
}
Roles
class Roles {
constructor() {
this.model = bookshelf.Model.extend({
tableName: 'roles',
privileges: function() {
return this.belongsToMany(Privileges.model).through(PrivilegeRole.model);
},
users: function() {
return this.hasMany(Users.model);
}
});
};
}
PrivilegeRole
class PrivilegeRole {
constructor() {
this.model = bookshelf.Model.extend({
tableName: 'privileges_roles',
role: function() {
return this.belongsTo(Roles.model);
},
privileges: function() {
return this.belongsTo(Privileges.model);
}
});
};
}
Those works really fine. Unfortunately when I'm trying to fetch Privileges from User model it keep inserting id instead of role_id to query.
class Users {
constructor() {
this.model = bookshelf.Model.extend({
tableName: 'users',
role: function () {
return this.belongsTo(Role.model);
},
privileges: function () {
// return this.belongsToMany(Privileges.model).through(PrivilegeRole.model);
return this.belongsToMany(Privileges.model, 'privileges_roles', 'role_id', 'privilege_id', 'role_id');
}
});
};
}
So at the end whatever I do, bookshelf is creating query like this:
select
privileges
.*,privileges_roles
.id
as_pivot_id
,privileges_roles
.role_id
as_pivot_role_id
,privileges_roles
.privilege_id
as_pivot_privilege_id
fromprivileges
inner joinprivileges_roles
onprivileges_roles
.privilege_id
=privileges
.id
whereprivileges_roles
.role_id
in (1)
Instead of role_id
in (3) like it's in a record fetched.
Alright so I've finally found a solution. Instead of previously used:
privileges: function () {
return this.belongsToMany(Privileges.model, 'privileges_roles', 'role_id', 'privilege_id', 'role_id');
}
I had to simply use:
privileges: function () {
return this.belongsToMany(Privileges.model).through(PrivilegeRole.model, 'role_id', 'privilege_id', 'role_id');
}
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.