ObjectionJs fetch entity with many to many relationship

I’m using knex-objection. I have a simple example of 3 tables: user, authority_user, authority where “user” and “authority” are joined together witha many to many relationship.

Relationship code:

static get relationMappings() {

    return {
        authorities: {
            relation: Model.ManyToManyRelation,
            modelClass: path.join(__dirname, 'Authority'),

            join: {
                from: 'user.id',
                through:{
                    from: 'user_authority.user_id',
                    to: 'user_authority.authority_id'
                },
                to: 'authority.id'
            }
        }
    }
}

The relationship works, i have inserted a user with one authority and checked it out. The problem is that eager loading a user with it’s authorities returns an undefined authorities array like the following:

  User {
id: 2,
username: 'someuser',
email: 'someuser@gmail.com',
password: '$2b$10$DztbTKBMsElxH0kk9nK8x.73bgl3W.rZnhzqFH5XRR2FSkYcROzm2',
is_active: 1,
created_at: '2021-12-28 18:10:30',
updated_at: '2021-12-28 18:10:30',
authorities: [ [Authority] ]

} ]

Here the authorities array is undefined whilei can clearly fetch relations and get my user’s authorities with : await User.relatedQuery(‘authorities’).for(2) which gives :

  sql: 'select `authority`.* from `authority` inner join `user_authority` on `authority`.`id` = `user_authority`.`authority_id` where `user_authority`.`user_id` in (?)'

RESULT: [ Authority { id: 1, name: ‘ROLE_USER’ } ]

EDIT: I tried to fetch a user with 2 authorities and this is the output:

User {
id: 3,
username: 'test',
email: 'test@gmail.com',
password: '$2b$10$3GWQd5b2.JwIvtyyOi/0zOKogY7kOG2aJhUqdFhlYpFvisPgeI62u',
is_active: 1,
created_at: '2021-12-29 08:42:50',
updated_at: '2021-12-29 08:42:50',
authorities: [ [Authority], [Authority] ]

}

it seems like ObjectionJs “knows” about the 2 Authority objections, but they just don’t “show up” and the authorities array is still undefined…

Reach Out And Grab Customers With Mobile Marketing Previous post Reach Out And Grab Customers With Mobile Marketing
Home Business Help You Should Not Miss Next post Home Business Help You Should Not Miss