Merging entities in TypeORM - mysql

I'm new to TypeORM and databases overall and I have simple question.
What is the way to 'merge' entities?
For example:
I have two entities, Product and Producer:
#Entity()
export class Product {
#PrimaryGeneratedColumn()
id: number;
#Column("int")
producer_id: number;
#Column()
producer: //I want show producer data here
#Column("varchar", { length: 255 })
name: string;
}
#Entity()
export class Producer {
#PrimaryGeneratedColumn()
id: number;
#Column()
name: string;
#Column()
logo: string;
}
As you can see, in Product entity I have producer_id property which contains ID of producer.
When I'm loading the product I want TypeORM to search through producers, get one with Id matching producer_id in Product and store it in producer property.
Maybe my question is little bit embroiled but I hope you'll get the point.
Thanks for all answers.

As far as I can see, you're looking for a one-to-many relation (one producer many products).
Check this doc from typeorm for further info. But basically do the following:
#Entity()
export class Product {
#PrimaryGeneratedColumn()
id: number;
#Column("int")
producer_id: number;
#ManyToOne(type => Producer, producer => producer.product)
producer: Producer
#Column("varchar", { length: 255 })
name: string;
}
#Entity()
export class Producer {
#PrimaryGeneratedColumn()
id: number;
#Column()
name: string;
#Column()
logo: string;
#OneToMany(type => Product, product => product.producer)
products: Product[]
}
And then in your queries specify relations to fetch:
productRepository.find({ relations: ["producer"] });
I'm not an user of typeorm, but it should be something like that

Related

Relations in Nest JS (Type ORM using SQL DB)

I am unable to understand relations basically I know the concept of relations but I am unable to us them in my project like m not getting what I want.
I don't know what is wrong here
import { ApiProperty } from '#nestjs/swagger';
import {
Entity,
Column,
PrimaryGeneratedColumn,
OneToOne,
JoinColumn,
} from 'typeorm';
import { Customer } from './Customer.entitye';
import { Sale } from './Sale.entity';
#Entity()
export class Mobile {
#PrimaryGeneratedColumn()
#ApiProperty()
id: number;
#Column()
#ApiProperty()
Mobile_name: string;
#Column()
#ApiProperty()
Mobile_Model: string;
#Column()
#ApiProperty()
Mobile_EMEI: String;
#Column()
#ApiProperty()
Mobile_Price: number;
#Column()
#ApiProperty()
Mobile_Color: string;
#OneToOne(() => Sale)
#JoinColumn()
Profile: Sale;
#OneToOne(() => Customer)
#JoinColumn()
customer: Customer;
}
and the second entity is
import { ApiProperty } from '#nestjs/swagger';
import { Entity, Column, PrimaryGeneratedColumn, OneToOne, JoinColumn } from 'typeorm';
import { Mobile } from './Mobile.entity';
#Entity()
export class Sale{
#PrimaryGeneratedColumn()
id:number
#Column()
#ApiProperty()
Sold_Mobile : String
#OneToOne(() => Mobile, (mobile) => mobile.Mobile_EMEI)
#JoinColumn()
mobile: Mobile
}
why this Mobileid is null
SS of DB
kindly give me the sol or just tell me the best source to learn thi thing

Typeorm, Define a new entity and populate it with default values and foreign keys

Let's say we have a user entity already defined and it has 3 rows. We create another entity called Usage after sometime and add one-to-one relation with User. Is it possible to prefill the usage table having 3 rows related to user table with default values ?
#Entity()
export class User {
#PrimaryGeneratedColumn()
id: number;
#Column()
username: string;
#Column()
password: string;
#OneToOne(() => Usage)
usage: Usage;}
#Entity()
export class Usage {
#PrimaryGeneratedColumn()
id: number;
#Column({default:0})
views: number;
#OneToOne(() => User)
#JoinColumn()
User: User; }

TypeORM MariaDB Primary Key as UUID

Having a really strange issue with TypeORM and MariaDB. I have two entities with UUIDs as the primary key. The Companies entity is working fine as it scaffolds the schema as CHAR but the users table is being instantiated as an auto increment INT.
User Entity
#Entity()
export class User {
#PrimaryGeneratedColumn('uuid')
id: string;
#Column()
firstname: string;
#Column()
lastname: string;
#Column({ unique: true })
email: string;
#Column()
password: string;
#ManyToOne(() => Company, (company) => company.users)
company: Company;
}
Companies Entity
#Entity()
export class Company {
#PrimaryGeneratedColumn('uuid')
id: string;
#Column()
name: string;
#OneToMany(() => User, (user) => user.company)
users: User[];
}
Config
const config: MysqlConnectionOptions = {
type: 'mariadb',
....
entities: ['dist/src/**/*.entity.js'],
synchronize: true,
};
Users Table Screenshot
Companies Table Screenshot
Find it really strange, is it because I'm using MariaDB instead of straight MySQL?
Okay looks like I fixed it, really odd one. Looks like something was cached incorrectly. Deleted dist folder and node modules. reinstalled and total recompile. Fixed...

TypeORM make COUNT query on table which maps two tables together

I have two entities Model and Video where Video basically store information about videos and Model store information about model. Because each video can have multiple models and each model can have multiple video entities looks like this:
How my entites and tables looks like:
// Video Entity
#Entity()
export class Video {
#PrimaryGeneratedColumn()
id?: number;
#Column({ charset: 'utf8mb4', collation: 'utf8mb4_unicode_ci' })
name: string;
#Column({ type: 'text', charset: 'utf8mb4', collation: 'utf8mb4_unicode_ci' })
description: string;
#ManyToMany((type) => Model)
#JoinTable()
models: Model[];
}
// Model Entity
#Entity()
export class Model {
#PrimaryGeneratedColumn()
id?: number;
#Column()
name: string;
#Column()
code: string;
}
Because there is relation #ManyToMany between model and video TypeORM also created one extra table for connecting this two. Table name is video_models_model and it looks like this:
+-----------+---------+
| videoId | modelId |
+===========+=========+
| 1 | 107 |
+-----------+---------+
| 2 | 142 |
+-----------+---------+
| 3 | 91 |
+-----------+---------+
What I need:
Based on modelId I need to find out COUNT() of videos.
In regular query language it would be something like:
SELECT model.*, COUNT(model_videos.videoId) as totalVideos FROM model as model
LEFT JOIN `video_models_model` `model_videos` ON `model_videos`.`modelId`=`model`.`id`
WHERE model.id = 1;
What I tried:
This is how regular query would looks like:
this.modelRepository
.createQueryBuilder('model')
.where('model.id = :id', { id: id })
.getOne();
so what I did was added to Model entity
#ManyToMany(type => Video)
#JoinTable()
videos: Video[];
and after that I tried
this.modelRepository
.createQueryBuilder('model')
.leftJoin('model.videos', 'videos')
.select('COUNT(videos)', 'totalVideos')
.where('model.id = :id', { id: id })
.getOne();
But it didn't work for me at all pluis it created one additional table named model_videos_video with modelId and videoId columns. So basically duplicate video_models_model table.
Is there any way how to make that easy query with TypeORM?
I found out that I have to change my entities to make them bi-directional so:
Video Entity:
#Entity()
export class Video {
#PrimaryGeneratedColumn()
id?: number;
#Column({ charset: 'utf8mb4', collation: 'utf8mb4_unicode_ci' })
name: string;
#Column({ type: 'text', charset: 'utf8mb4', collation: 'utf8mb4_unicode_ci' })
description: string;
#ManyToMany(type => Model, model => model.videos)
#JoinTable()
models: Model[];
}
Model Entity:
#Entity()
export class Model {
#PrimaryGeneratedColumn()
id?: number;
#Column()
name: string;
#Column()
code: string;
#ManyToMany(type => Video, video => video.models)
videos: Video[];
}
And after that I make query like this:
this.modelRepository
.createQueryBuilder('model')
.loadRelationCountAndMap('model.videoCount', 'model.videos')
.where('model.id = :id', { id: id })
.getOne();

Two entity have each other

In this case, the store can have many owners, and the owners can have many store.
However, when i save the entity by using Repository and the problem happen:
Maximum call stack size exceeded
I think it need to use Nested Tree annotation? But i dont know how to correct it. Please help!
#Entity('store')
export class StoreEntity {
#PrimaryGeneratedColumn('uuid')
id: string;
#Column()
name: string;
...
#ManyToMany(type => UserEntity, user => user.ownStores)
#JoinTable()
owners: UserEntity[];
}
#Entity('user')
export class UserEntity {
#PrimaryGeneratedColumn('uuid')
id: string;
#Column({
type: 'varchar',
})
email: string;
...
#ManyToMany(type => StoreEntity, store => store.owners)
ownStores: StoreEntity[];