Cannot use has in the name of pivot table - TypeORM - node.js

#Entity('projects')
export class ProjectEntity extends BaseEntity {
#PrimaryGeneratedColumn()
id: number;
#ManyToMany(() => UserEntity, object => object.project, { cascade: true })
#JoinTable({name:'project_has_users'})
users: UserEntity[];
#Column()
name: string;
}
#Entity('users')
export class UserEntity {
#PrimaryGeneratedColumn()
id: number;
#ManyToMany(() => ProjectEntity, object => object.users)
project: ProjectEntity[];
#Column()
#IsEmail()
email: string;
}
QueryFailedError: null value in column "projectsId" of relation "project_has_users" violates not-null constraint

Related

Can't see the ID of the hotel table in adminjs

I have 2 fields which are named hotel and hotel description. In admin page when I add the hotel ID to hotel description image 1. But in the hotel description table on the admin page, the id is not visible image 2.
Here is typeorm entities for them.
Hotel.entity
#Entity()
export class Hotel extends BaseEntity {
#PrimaryGeneratedColumn("uuid")
id: string;
#Column({ unique: true, nullable: true })
hotelName: string;
#OneToMany(
() => HotelDescription,
(hotelDescription) => hotelDescription.hotel,
)
hotelDescriptions: HotelDescription[];
#OneToMany(() => Reservation, (reservation) => reservation.hotel)
reservations: Reservation[];
}
HotelDescription.entity
#Entity()
export class HotelDescription extends BaseEntity {
#PrimaryGeneratedColumn("uuid")
id: string;
#Column({ type: "text", enum: Language, nullable: true })
language: Language;
#Column()
name: string;
#Column()
description: string;
#OneToOne(() => Service, (service) => service.hotelDescription)
services: Service;
#OneToMany(() => Treatment, (treatment) => treatment.hotelDescription)
treatments: Treatment[];
#ManyToOne(() => Hotel, (hotel) => hotel.hotelDescriptions)
hotel: Hotel;
}
I tried to #JoinColumn to try to add hotelId to the entity but that failed (removed in the code above)

How to create migration for entities with properties that have relation #ManyToOne and #OneToMany with TypeORM?

I have 5 entities: User, Todos, Project, Section and Label. Relationships happen as follows:
Each User is associated with multiples Todo.
Each Todo is associated with a single User, Project and Section, and is associated with multiples Label.
Each Project is associated with a single User.
Each Section is associated with a single Project.
Each Label is associated with a single Todo.
The migration code to the #OneToOne relationship is done using the createForeignKey method, as done for project_id column at Section entity:
import {
MigrationInterface,
QueryRunner,
TableColumn,
TableForeignKey,
} from 'typeorm';
export class AddProjectIdToSections1669830961233 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.addColumn(
'sections',
new TableColumn({
name: 'project_id',
type: 'uuid',
isNullable: true,
})
);
await queryRunner.createForeignKey(
'sections',
new TableForeignKey({
name: 'SectionsProject',
columnNames: ['project_id'],
referencedTableName: 'projects',
referencedColumnNames: ['id'],
onDelete: 'SET NULL',
})
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropForeignKey('sections', 'SectionsProject');
await queryRunner.dropColumn('sections', 'project_id');
}
}
However, how do you use createForeignkey for relations of #OneToMany and #ManyToOne, and especially when the two happen round trip?
Entities code:
// User.entity.ts
import {
Column,
CreateDateColumn,
Entity,
OneToMany,
PrimaryGeneratedColumn,
} from 'typeorm';
import { Todo } from './Todo.entity';
#Entity('users')
export class User {
#PrimaryGeneratedColumn('uuid')
id: string;
#Column()
name: string;
#Column()
email: string;
#Column()
password: string;
#Column({ nullable: true })
photoURL: string;
#Column()
language: string;
#CreateDateColumn()
created_at: Date;
#OneToMany(() => Todo, (todo) => todo.user)
todos: Todo[];
}
// Todo.entity.ts
import {
Column,
Entity,
JoinColumn,
ManyToOne,
OneToMany,
OneToOne,
PrimaryGeneratedColumn,
} from 'typeorm';
import { IProject } from '../types';
import { Label } from './Label.entity';
import { Project } from './Project.entity';
import { Section } from './Section.entity';
import { User } from './User.entity';
#Entity('todos')
export class Todo {
#PrimaryGeneratedColumn('uuid')
id: string;
#Column()
title: string;
#Column()
description?: string;
#Column()
type: string;
#Column({ type: 'timestamptz' })
date: Date;
#Column()
priority: number;
#Column()
isCompleted: boolean;
#OneToOne(() => Project)
#JoinColumn({ name: 'project_id' })
project: IProject;
#OneToOne(() => Section)
#JoinColumn({ name: 'section_id' })
section?: Section;
#OneToMany(() => Label, (label) => label.todo, {
cascade: true,
})
labels: Label[];
#ManyToOne(() => User, (user) => user.todos)
#JoinColumn({ name: 'user_id' })
user: User;
}
// Project.entity.ts
import {
Column,
Entity,
JoinColumn,
OneToOne,
PrimaryGeneratedColumn,
} from 'typeorm';
import { User } from './User.entity';
#Entity('projects')
export class Project {
#PrimaryGeneratedColumn('uuid')
id: string;
#Column()
type: string;
#Column()
title: string;
#Column()
colorName: string;
#Column()
class: string;
#OneToOne(() => User)
#JoinColumn({ name: 'user_id' })
user: User;
}
// Section.entity.ts
import {
Column,
Entity,
JoinColumn,
OneToOne,
PrimaryGeneratedColumn,
} from 'typeorm';
import { Project } from './Project.entity';
#Entity('sections')
export class Section {
#PrimaryGeneratedColumn('uuid')
readonly id: string;
#Column()
index: number;
#Column()
type: string;
#Column()
title: string;
#Column({ type: 'timestamptz' })
readonly date: Date;
#OneToOne(() => Project)
#JoinColumn({ name: 'project_id' })
project: Project;
}
// label.entity.ts
import {
Column,
Entity,
JoinColumn,
ManyToOne,
PrimaryGeneratedColumn,
} from 'typeorm';
import { Todo } from './Todo.entity';
#Entity('labels')
export class Label {
#PrimaryGeneratedColumn('uuid')
id: string;
#Column()
type: string;
#Column()
title: string;
#Column()
colorName: string;
#Column()
class: string;
#ManyToOne(() => Todo, (todo) => todo.labels)
#JoinColumn({ name: 'todo_id' })
todo: Todo;
}

Retriving data from postgres using typeorm

I am trying to fetch data using Typeform in my NestJs project.
I am trying to join three tables.
User table
Roles and user forginkey table (connect between tables 1 & 3)
Roles table
My user table entity
#Entity()
export class Users {
#PrimaryGeneratedColumn()
id: number;
#Column()
email: string;
#Column()
passwordHash: string;
#Column()
firstName: string;
#Column()
lastName: string;
#Column()
registerTimestamp: Date;
#Column({ default: false })
isActive: boolean;
#OneToOne(() => UsersRole)
#JoinColumn({ name: 'id' })
users_role: UsersRole;
}
My Users_Roles code
#Entity()
export class UsersRole {
#PrimaryColumn()
user_id: number;
#PrimaryColumn()
role_id: number;
#OneToOne(() => UsersRole)
#JoinColumn({ name: 'role_id' })
roles: UsersRole;
}
My Roles table code
#Entity()
export class UsersRole {
#PrimaryColumn()
id: number;
#PrimaryColumn()
role: string;
}
How do I join between them three tables using Typeform?

Find - relations xxx not found

I am trying to return and entity including its relation but I am getting an error saying relation xxx not found. I am using the repository pattern.
#Entity({ name: 'person' })
export class PersonEntity {
#PrimaryGeneratedColumn('uuid')
id: string;
#Column({ type: 'number' })
statusId: number;
#ManyToOne(() => StatusEntity, status => status.id)
status: StatusEntity;
}
#Entity({ name: 'statuses' })
export class StatusEntity {
#PrimaryGeneratedColumn('increment')
id: number;
#Column({ type: 'varchar', length: 256 })
name: string;
}
I am using postgres and I have a foreign key declared:
"public"."person" ADD CONSTRAINT "FK_person_statusid" FOREIGN KEY ("statusId") REFERENCES "public"."statuses"("id")
In my service:
public async getAll(): Promise<PersonEntity[]> {
return await this.personRepository.find({ relations: ['statuses'] });
}
#Entity({ name: 'person' })
export class PersonEntity {
#PrimaryGeneratedColumn('uuid')
id: string;
#Column({ type: 'number' })
statusId: number;
#ManyToOne(() => StatusEntity)
#JoinTable()
status: StatusEntity;
}
#Entity({ name: 'status' })
export class StatusEntity {
#PrimaryGeneratedColumn()
id: number;
#Column({ type: 'varchar', length: 256 })
name: string;
}
Note that I have changed StatusEntity name from statuses to status.
Could you delete the foreign key you created manually, and then update your entity like below and try?
#Entity({ name: 'person' })
export class PersonEntity {
#PrimaryGeneratedColumn('uuid')
id: string;
#Column({ type: 'number' })
statusId: number;
#ManyToOne(() => StatusEntity)
#JoinColumn({ name: 'statusId })
status: StatusEntity;
}

One-to-one and one-to-many with same entity

I have two entities user and address. So user can have multiple address (oneTomany) and also each user also have primaryAddress(one-to-one) relationship with address entity. How can I design this both entities?
import {Entity, PrimaryGeneratedColumn, Column} from "typeorm";
#Entity()
export class User {
#PrimaryGeneratedColumn()
id: number;
#Column()
name: string;
#OneToMany((type) => Address, (address) => address.user)
addresses: Address[];
#OneToOne((type) => Address)
primaryAddress: Address;
}
import {Entity, PrimaryGeneratedColumn, Column} from "typeorm";
#Entity()
export class Address {
#PrimaryGeneratedColumn()
id: number;
#Column()
addr1: string;
#Column()
addr2: string;
#Column()
city: string;
#Column()
state: string;
#Column()
zip: string;
#Column()
isPrimaryAddress: boolean;
#ManyToOne((type) => User, (user) => user.addresses)
user: User;
}

Resources