And when using #BeforeInsert(), #BeforeUpdate() are recorded, but I don't need this behavior.
There are Entitys: Driver, Truck, Trip.
Trip has a relationship with the Truck and Driver tables.
Trip has a name_trip field, which should be generated and updated when the associated Driver, Truck data changes.
I'm trying to use Trip
#AfterInsert(), // #AfterUpdate()
Driver:
#Entity()
export class Driver extends BaseEntity {
#PrimaryGeneratedColumn()
id: number;
#Column()
DriverName: string;
}
Truck:
#Entity()
export class Truck extends BaseEntity {
#PrimaryGeneratedColumn()
id: number;
#Column()
AutoData: string;
}
Trip:
#Entity()
export class Trip extends BaseEntity {
#PrimaryGeneratedColumn()
id: number;
#OneToOne(() => Truck, (truck) => truck.id, { nullable: true, eager: true })
#JoinColumn()
truck: Truck;
#OneToOne(() => Driver, (drive) => drive.DriverName, { nullable: true, eager: true }) // eager: true }
#JoinColumn()
driver: Driver;
#Column({ unique: true, nullable: true })
name_trip: string;
#AfterInsert()
// #BeforeInsert()
#BeforeUpdate()
// #AfterUpdate()
updateNameTrip() {
try {
let driverName = '';
let autoData = '';
console.log('this.driver', this.driver);
if (!this.driver) {
console.log('DriverName = Null');
driverName = Driver not found';
} else {
driverName = this.driver.DriverName;
}
if (!this.truck) {
console.log('AutoData = Null');
autoData = Auto not found';
} else {
autoData = this.truck.AutoData;
}
const name_trip = `${uuidv4()}: ID Trip: ${this.id}, driver:
${driverName}, autoData: ${autoData}`;
this.name_trip = name_trip;
console.log('name_trip', name_trip);
} catch (e) {
console.log('Entity Trip Error:', e);
}
}
}
Related
I'm trying to make API pagination for GET /authors.
I have bidirectional many to many relation between authors and books table.
I found that problem is when using creatingQueryBuilder() in combination with .leftJoinAndSelect() and .skip() I get TypeORMError: ""authors"" alias was not found. Maybe you forgot to join it?. But I'm not sure how to solve it.
My database look like this:
library=# select * from authors;
id | first_name | last_name | birth_date | created_at | updated_at
----+------------+-----------+------------+----------------------------+----------------------------
library=# select * from books;
id | title | isbn | pages | created_at | updated_at
----+------------------+-----------------------+-------+----------------------------+----------------------------
library=# select * from books_authors
books_id | authors_id
----------+------------
(4 rows)
Entities look like this:
import { Exclude } from 'class-transformer';
import { BookEntity } from 'src/book/entities/book.entity';
import {
Entity,
PrimaryGeneratedColumn,
Column,
BeforeInsert,
ManyToMany,
} from 'typeorm';
#Entity({ name: 'authors' })
export class AuthorEntity {
#Exclude()
#PrimaryGeneratedColumn()
id: number;
#Column()
firstName: string;
#Column()
lastName: string;
#Column({ type: 'date', nullable: true })
birthDate: Date | null;
#Exclude()
#Column({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' })
createdAt: Date;
#Exclude()
#Column({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' })
updatedAt: Date;
#ManyToMany(() => BookEntity, (book) => book.authors)
books: BookEntity[];
#BeforeInsert()
updateTimestamp() {
this.updatedAt = new Date();
}
}
import { Exclude } from 'class-transformer';
import { AuthorEntity } from 'src/author/entities/author.entity';
import {
Entity,
PrimaryGeneratedColumn,
Column,
BeforeInsert,
ManyToMany,
JoinTable,
} from 'typeorm';
#Entity({ name: 'books' })
export class BookEntity {
#Exclude()
#PrimaryGeneratedColumn()
id: number;
#Column()
title: string;
#Column()
isbn: string;
#Column()
pages: number;
#Exclude()
#Column({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' })
createdAt: Date;
#Exclude()
#Column({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' })
updatedAt: Date;
#ManyToMany(() => AuthorEntity, (author) => author.books)
#JoinTable({ name: 'books_authors' })
authors: AuthorEntity[];
#BeforeInsert()
updateTimestamp() {
this.updatedAt = new Date();
}
}
Service method looks like this:
async findAll(
pageOptionsDto: PageOptionsDto,
filterAuthorDto: FilterAuthorDto,
): Promise<PageDto<AuthorEntity>> {
const builder = this.dataSource
.getRepository(AuthorEntity)
.createQueryBuilder('authors');
if (filterAuthorDto?.firstName) {
builder.where('"authors"."first_name" LIKE :firstName', {
firstName: `%${filterAuthorDto.firstName}%`,
});
}
if (filterAuthorDto?.lastName) {
builder.andWhere('"authors"."last_name" LIKE :lastName', {
lastName: `%${filterAuthorDto.lastName}%`,
});
}
// This part of code is problematic
builder
.innerJoinAndSelect('authors.books', 'books')
.orderBy('"authors"."created_at"', pageOptionsDto.order)
.skip(pageOptionsDto.skip)
.take(pageOptionsDto.perPage);
const total = await builder.getCount();
const { entities } = await builder.getRawAndEntities();
const pageMetaDto = new PageMetaDto({ total, pageOptionsDto });
return new PageDto(entities, pageMetaDto);
}
Just remove the double quotation inside the string, it's redundant and makes typeorm get confused and couldn't find related defined alias.
...
.orderBy('authors.created_at', pageOptionsDto.order)
...
I got an error when I pass an empty string to completed but when I pass empty string to delivery_name is work fine
const queryBuilder = this.deliveryRepository
.createQueryBuilder('delivery')
.select([
'delivery.delivery_id AS delivery_id',
'delivery.price AS price',
'delivery.delivery_date AS invoice_date',
'delivery.invoice_id AS invoice_id',
'delivery.completed AS completed',
'delivery.deliveryman_id AS deliveryman_id',
'deliveryman.delivery_name AS delivery_name',
'deliveryman.vehicle AS vehicle',
'deliveryman.phone AS phone',
]).orWhere('LOWER(deliveryman.delivery_name) LIKE LOWER(:delivery_name)', {
delivery_name: `%${option.filter}%`,
}).orWhere('delivery.completed = :completed', {
completed: `%${option.filter}%`,
})
DeliveryEntity
import { DeliveryManEntity, InvoiceEntity } from '#entity';
import { DeliveryStatus } from '../../../constant/delivery/delivery-status';
import {
Column,
Entity,
JoinColumn,
ManyToOne,
OneToOne,
PrimaryGeneratedColumn,
} from 'typeorm';
import { ShareEntity } from '#share-entity';
#Entity({ name: 'delivery' })
export class DeliveryEntity extends ShareEntity {
#PrimaryGeneratedColumn()
delivery_id: number;
#Column({ nullable: true, default: 0 })
price: number;
#Column({ type: 'date', default: () => 'NOW()' })
delivery_date: Date;
#OneToOne(() => InvoiceEntity, (entity) => entity.delivery)
#JoinColumn({ name: 'invoice_id', referencedColumnName: 'invoice_id' })
invoice: InvoiceEntity;
#Column()
invoice_id: number;
#Column({
enum: DeliveryStatus,
type: 'enum',
default: DeliveryStatus.PENDING,
enumName: 'delivery_status',
name: 'completed',
})
completed: DeliveryStatus;
#ManyToOne(() => DeliveryManEntity, (entity) => entity.delivery)
#JoinColumn({
name: 'deliveryman_id',
referencedColumnName: 'deliveryman_id',
})
deliveryman: DeliveryManEntity;
#Column()
deliveryman_id: number;
}
Delivery Status
export enum DeliveryStatus {
PENDING = 'PENDING',
COMPLETED = 'COMPLETED',
}
I want to pass an empty string to completed or I can pass PENDING OR COMPLETED
any solution how to query with empty string to completed field
I'm using typeorm + Nestjs +Postgresql
Based on your comment, what you should be doing is something like below:
const queryBuilder = this.deliveryRepository
.createQueryBuilder('delivery')
.select([
'delivery.delivery_id AS delivery_id',
'delivery.price AS price',
'delivery.delivery_date AS invoice_date',
'delivery.invoice_id AS invoice_id',
'delivery.completed AS completed',
'delivery.deliveryman_id AS deliveryman_id',
'deliveryman.delivery_name AS delivery_name',
'deliveryman.vehicle AS vehicle',
'deliveryman.phone AS phone',
]).orWhere('LOWER(deliveryman.delivery_name) LIKE LOWER(:delivery_name)', {
delivery_name: `%${option.filter}%`,
});
const filter = `%${option.filter}%`;
if (filter === "") {
queryBuilder.orWhere('delivery.completed IN (...:completed)', {
completed: [DeliveryStatus.COMPLETED, DeliveryStatus.PENDING],
});
} else {
queryBuilder.orWhere('delivery.completed = :completed', {
completed: filter,
});
}
There are two entities as follow:
// user.entity.ts
#Entity()
export class User extends BaseEntity {
#PrimaryGeneratedColumn()
id: number;
#Column()
#RelationId((user: User) => user.group)
groupId: number;
#Column()
fullName: string;
#Column()
email: string;
#Column()
passwordHash: string;
#ManyToOne(type => Group, group => group.users)
#JoinColumn()
group: Group;
isOwner: boolean;
}
// group.entity.ts
#Entity()
export class Group extends BaseEntity {
#PrimaryGeneratedColumn()
id: number;
#Column()
name: string;
#Column({ default: false })
isOwner: boolean;
#OneToMany(type => User, user => user.group)
users: User[];
}
I'd like to map the isOwner value of Group to isOwner of User
I tried:
async findOneById(id: number): Promise<User> {
return await User.createQueryBuilder('user')
.leftJoinAndMapOne('user.isOwner', 'user.group', 'group')
.select(['user.id', 'user.fullName', 'user.email', 'group.isOwner'])
.getOne();
}
the result was:
It is possible to achieve that by using #AfterLoad() or with JS or with raw query.
BUT
Is it possible to implement that using the orm on the query level?
Something like that could be as a solution:
findOneById(id: number): Promise<User> {
return User.createQueryBuilder('user')
.leftJoinAndMapOne('user.isOwner', 'user.group', 'group')
.select(['user.id', 'user.fullName', 'user.email', 'group.isOwner AS user.isOwner']) // or probably 'group.isOwner AS user_isOwner'
.getOne();
}
And you could look at this answer, hope it would be helpful
I have two entities called User and Ad and the relation is 1:M, when I need to create a new Ad, I need to pass the announcer_id together.
Ad.ts
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn,
ManyToOne,
JoinColumn,
} from 'typeorm';
import User from './User';
#Entity('ads')
class Ad {
#PrimaryGeneratedColumn('uuid')
id: string;
#Column()
announcer_id: string;
#ManyToOne(() => User)
#JoinColumn({ name: 'announcer_id' })
announcer: User;
}
export default Ad;
User.ts
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn,
} from 'typeorm';
#Entity('users')
class Ad {
#PrimaryGeneratedColumn('uuid')
id: string;
#Column()
name: string;
#Column()
email: string;
#Column()
password: string;
#CreateDateColumn()
created_at: Date;
#UpdateDateColumn()
updated_at: Date;
}
export default Ad;
CreateAdService.ts
import { getCustomRepository } from 'typeorm';
import Ad from '../models/Ad';
import AdsRepository from '../repositories/AdsRepository';
interface IRequest {
announcer_id: string;
title: string;
description: string;
price: number;
n_room: number;
n_bathroom: number;
garage: boolean;
}
class CreateAdService {
public async execute({
announcer_id,
title,
description,
price,
n_room,
n_bathroom,
garage,
}: IRequest): Promise<Ad> {
const adsRepository = getCustomRepository(AdsRepository);
const priceNegative = adsRepository.isNegative(price);
if (priceNegative) {
throw new Error("You can't create an announcement with negative price.");
}
const ad = adsRepository.create({
announcer_id,
title,
description,
price,
n_room,
n_bathroom,
garage,
});
await adsRepository.save(ad);
return ad;
}
}
export default CreateAdService;
The Error
{
"error": "Cyclic dependency: \"Ad\""
}
Below I have the Equipt entity it has three columns createdById, tribeId, userId.
I am trying to save a new row using the id's of each entity, and not the entities themselves:
This doesn't work:
let e = connection.getRepository(Equipt);
const check = await e.save({
userId: 1,
tribeId: 1,
createdById: 1,
})
This works:
let e = connection.getRepository(Equipt);
const check = await e.save({
user: user,
tribe: tribe,
createdBy: adminUser,
})
Entity:
import {ManyToOne, RelationId, JoinColumn, Entity} from "typeorm";
import {User} from './User';
import { Base } from "../base";
import { Tribe } from "./Tribe";
#Entity('Equipts')
export class Equipt extends Base {
#ManyToOne(type => User, { nullable: false })
#JoinColumn()
createdBy: User;
#RelationId((Equipt: Equipt) => Equipt.createdBy)
createdById: number;
#ManyToOne(type => Tribe, { nullable: false })
#JoinColumn()
Tribe: Tribe;
#RelationId((Equipt: Equipt) => Equipt.Tribe)
TribeId: number;
#ManyToOne(type => User, { nullable: false })
#JoinColumn()
user: User;
#RelationId((Equipt: Equipt) => Equipt.user)
userId: number;
}
Is there any way to insert using id's without having the pass the entire entity?