Loopback4多对多关系,但在关系表中没有额外的id字段作为主键

时间:2019-07-04 06:41:21

标签: typescript strongloop loopback v4l2loopback

我正在为具有多个关系的现有数据库创建应用程序,如下所示:

表格用户:
Id int主键

表角色:
Id int主键

表UserRoles:
UserId int主键和User.Id的外键
RoleId 完整的Role.Id主键和外键

现在的目标是在LoopBack4中实现多对多关系,而我被困在这一点上,一个模型必须包含至少一个id / pk属性enter image description here

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

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

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;
    }
}

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

0 个答案:

没有答案
相关问题