One-to-one and one-to-many with same entity - node.js

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

Related

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?

Cannot use has in the name of pivot table - TypeORM

#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

typeorm shows me this error: TypeError: Object prototype may only be an Object or null: undefined

I am new at typeorm and I created a user entity like this:
User.ts:
import {DefaultBaseEntity} from "../defaults/DefaultBaseEntity";
import {Entity, Column} from "typeorm";
#Entity("users")
export class User extends DefaultBaseEntity {
#Column()
username: string;
#Column()
email: string;
#Column()
password: string;
#Column()
account_type: string;
#Column()
photo_url: string;
#Column()
discipline: string;
#Column()
class: string;
#Column()
confirmed: number;
}
and this is DefaultBaseEntity.ts
import { BaseEntity, PrimaryGeneratedColumn, Column } from "typeorm";
export declare class DefaultBaseEntity extends BaseEntity {
#PrimaryGeneratedColumn()
id: string;
#Column()
createdAt: Date;
#Column()
updatedAt: Date;
constructor();
}
when I run the app it returns me this error: TypeError: Object prototype may only be an Object or null: undefined for running the app I use ts-node. What I missed?

how to make relationship on typeOrm

How do I define a relationship?
#Entity('favoritesable')
export class FavoritesEntity extends BaseEntity {
#PrimaryGeneratedColumn()
id: number;
#Column()
favoritesableId: number; // foreing key ( ads id, blog id, user id )
#Column()
favoritesableType: string; // ads, blog, user
#Column()
userId: number;
}
ads entity:
#Entity('ads')
export class AdsEntity extends BaseEntity {
#PrimaryGeneratedColumn()
id: number;
// How do I define a relationship to FavoritesEntity ?
}
data example for favoritesable table :
{id: 1, favoritesableId: 1, favoritesableType: "ads", userId: 1},
{id: 2, favoritesableId: 4, favoritesableType: "ads", userId: 1},
{id: 3, favoritesableId: 1, favoritesableType: "ads", userId: 2},
how to make this relation on ads entity and favorites Entity ?
TypeORM's documentation pretty clearly shows ow to make a relationship between entities.
Example pulled from their docs:
import {Entity, PrimaryGeneratedColumn, Column, ManyToMany} from "typeorm";
import {Question} from "./Question";
#Entity()
export class Category {
#PrimaryGeneratedColumn()
id: number;
#Column()
name: string;
#ManyToMany(type => Question, question => question.categories)
questions: Question[];
}
import {Entity, PrimaryGeneratedColumn, Column, ManyToMany, JoinTable} from "typeorm";
import {Category} from "./Category";
#Entity()
export class Question {
#PrimaryGeneratedColumn()
id: number;
#Column()
title: string;
#Column()
text: string;
#ManyToMany(type => Category, category => category.questions)
#JoinTable()
categories: Category[];
}

Resources