1

I'm building up an application for an already existing and used database with a Many-to-Many relation looking like this:

Table User:
Id int primary key

Table Role:
Id int primary key

Table UserRoles:
UserId int primary key and foreign key to User.Id
RoleId int primary key and foreign key to Role.Id

Now the goal is to implement the many-to-many relation in LoopBack4 and i'm stuck at the point, that a model has to include at least one id/pk property: enter image description here

I used this thread: Loopback 4: Many to Many Relation to build up the application till this point. But in that example, there is an extra id field inside the relation table. The point is, i can not alter the table due to the fact, that the database is already in use and i have to work with it.

So my code is currently looking like this:

user.model.ts

import {Entity, hasMany, model, property} from '@loopback/repository';
import {UserRole} from "./user-role.model";

@model({settings: {}})
export class User extends Entity {
  @property({
    type: 'number',
    id: true,
    required: true,
  })
  Id: number;

  // ... all the other properties ...

  @hasMany(() => UserRole, {keyTo: 'UserId'})
  UserRoles?: UserRole[];

  constructor(data?: Partial<User>) {
    super(data);
  }
}

export interface UserRelations {
  // describe navigational properties here
}

export type UserWithRelations = User & UserRelations;

user-role.model.ts

import {belongsTo, Entity, model} from '@loopback/repository';
import {User} from "./user.model";
import {Role} from "./role.model";

@model({
           settings: {},
           name:     'UserRoles'
       })
export class UserRole extends Entity
{
    @belongsTo(() => User)
    UserId: number;

    @belongsTo(() => Role)
    RoleId: number;


    constructor(data?: Partial<UserRole>)
    {
        super(data);
    }
}

export interface UserRoleRelations
{
    // describe navigational properties here
}

export type UserRoleWithRelations = UserRole & UserRoleRelations;

user.repository.ts

import {DefaultCrudRepository, Filter, Getter, HasManyRepositoryFactory, Options, repository} from '@loopback/repository';
import {User, UserRelations, UserRole, UserWithRelations} from '../models';
import {MySqlDataSource} from '../datasources';
import {inject} from '@loopback/core';
import {UserRoleRepository} from "./user-role.repository";

export class UserRepository extends DefaultCrudRepository<User, typeof User.prototype.Id, UserRelations>
{
    public readonly UserRoles: HasManyRepositoryFactory<UserRole, typeof UserRole.prototype.UserId>;


    constructor(
        @inject('datasources.MySQL') dataSource: MySqlDataSource,
        @repository.getter('UserRoleRepository') getUserRoleRepository: Getter<UserRoleRepository>)
    {
        super(User, dataSource);
        this.UserRoles = this.createHasManyRepositoryFactoryFor('UserRoles', getUserRoleRepository);
    }


    async find(filter?: Filter<User>, options?: Options): Promise<UserWithRelations[]>
    {
        // Prevent juggler for applying "include" filter
        // Juggler is not aware of LB4 relations
        const include = filter && filter.include;
        filter        = {...filter, include: undefined};

        const result  = await super.find(filter, options);

        const includeRelations = include ? include.map(x => x.relation) : [];

        // poor-mans inclusion resolver, this should be handled by DefaultCrudRepo
        // and use `inq` operator to fetch related roles in fewer DB queries
        // this is a temporary implementation, please see
        // https://github.com/strongloop/loopback-next/issues/3195
        if(includeRelations.includes('Roles'))
        {
            await Promise.all(result.map(async u =>
                                         {
                                             u.UserRoles = await this.UserRoles(u.Id).find();
                                         }));
        }

        return result;
    }
}

What do i have to do, to get the Roles assigned to the user? As far as i understand, i need to build up the hasMany-Relation. But the loopback cli is breaking with the error from above and i do not see, what i have to do now.

MIB
  • 337
  • 2
  • 15

0 Answers0