V
V
vaflya2020-09-04 15:43:55
Database
vaflya, 2020-09-04 15:43:55

How to make in TypeORM, OneToOne relationship without changing the structure of the database?

Good afternoon! There is a DB (the rights only to reading). I describe essences of 2 tables.
1 -User.entity.ts
List of users

import { Entity, PrimaryColumn, Column, Timestamp, OneToOne, JoinColumn } from 'typeorm';
import ModelHasRoles from './modelHasRoles.entity';

@Entity({
    name: 'user'
})
export default class User {
    @PrimaryColumn({
        type: 'integer'
    })
    id: number;

    @OneToOne(() => ModelHasRoles, role => role.modelId)
    role: ModelHasRoles
    ....
}


2- ModelHasRoles.entity.ts
There is written a role for each user

import { Entity, PrimaryColumn, Column, OneToOne, JoinColumn } from 'typeorm';
import User from './user.entity';

@Entity({
    name: 'model_has_roles'
})
export default class ModelHasRoles {
    @PrimaryColumn({
        name: 'role_id',
        type: 'integer'
    })
    roleId: number;

    @OneToOne(() => User, user => user.id)
    user: User;

    @Column({
        name: 'model_type',
        type: 'varchar',
        length: 255
    })
    modelType: string;

    @Column({
        name: 'model_id',
        type: 'bigint'
    })
    modelId: number;
}


User.id == ModelHasRole.modelId


I can’t build a relationship so that when you get rows from the User table, fields from ModelHasRole are pulled up.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question