1

我正在为一个已经存在和使用的数据库构建一个应用程序,该数据库具有如下所示的多对多关系:

表用户:
Id int 主键

表角色:
id int 主键

表 UserRoles:
UserId int 主键和外键到 User.Id
RoleId int 主键和外键到 Role.Id

现在的目标是在 LoopBack4 中实现多对多关系,我被困在这一点上,模型必须至少包含一个 id/pk 属性在此处输入图像描述

到目前为止,我使用了这个线程:Loopback 4: Many to Many Relation来构建应用程序。但是在那个例子中,关系表中有一个额外的 id 字段。关键是,我无法更改表,因为数据库已经在使用中,我必须使用它。

所以我的代码目前看起来像这样:

用户模型.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;

用户角色.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;

用户.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;
    }
}

我必须做什么才能获得分配给用户的角色?据我了解,我需要建立hasMany-Relation。但是环回 cli 因上面的错误而中断,我看不到,我现在必须做什么。

4

0 回答 0