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

问题描述 投票:1回答:1

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

表用户:Id int主键

表角色:Id int主键

表UserRoles:UserId int主键和User.Id的外键RoleId int主键和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打破了上面的错误,我看不到,我现在要做的是。

我正在为具有多对多关系的现有数据库和已使用数据库构建应用程序,如下所示:表用户:Id int主键表角色:Id int主键表...

typescript strongloop loopback v4l2loopback
1个回答
0
投票

表应该始终具有主键或ID,即使您不需要它(尚未)。将ID属性添加到UserRole表中,然后就可以从错误继续了:

© www.soinside.com 2019 - 2024. All rights reserved.