当前位置:网站首页>Typeorm framework
Typeorm framework
2022-07-01 05:25:00 【BloggerM】
TypeORM frame
know TypeORM
TypeORMIt's aORM(opens new window) frame , It can run inNodeJS、Browser、Cordova、PhoneGap、Ionic、React Native、ExpoandElectronOn the platform , It can be done withTypeScriptandJavaScript(ES5,ES6,ES7,ES8) Use it together . Its goal is to always support the latestJavaScriptFeatures and provide additional features to help you develop anything that uses a database ( Whether it's a small application with only a few tables or a large enterprise application with multiple databases ) Applications .- It's different from all the other things that exist
JavaScript ORMframe ,TypeORMSupportActive RecordandData MapperPattern , This means that you can write high-quality 、 Loosely coupled 、 Extensible 、 Maintainable applications .
TypeORM Characteristics of
- Support
DataMapperandActiveRecord( It's up to you ) - Entities and columns
- Database property column type
- Entity management
- Repositories and custom repositories
- Clear object relationship model
- relation ( Relationship )
- Greed and procrastination
- One way , Bidirectional and self referential relationships
- Support multiple inheritance mode
- cascade
- Indexes
- Business
- Migration and automatic migration
- Connection pool
- Master slave copy
- Use multiple database types
- Cross database and cross schema queries
- Elegant grammar , Flexible and powerful
QueryBuilder - Left join and inner join
- Use the appropriate paging of the associated query
- The query cache
- Raw result stream
- journal
- Listeners and subscribers ( hook )
- Support closure table mode
- Declare the schema in the model or separate configuration file
json / xml / yml / envFormat connection configuration- Support
MySQL / MariaDB / Postgres / SQLite / Microsoft SQL Server / Oracle / sql.js - Support
MongoDB NoSQLdatabase - Can be found in
NodeJS / browser / Ionic / Cordova / React Native / Expo / ElectronOn the platform - Support
TypeScriptandJavaScript - Generate high performance 、 flexible 、 Clear and maintainable code
- Follow all possible best practices
- Command line tools
install ( One )
- adopt
npminstall :npm install typeorm --save
- You also need to install
reflect-metadata:npm install reflect-metadata --save
- And you need to import... In the global location of the application ( For example, in
app.tsin )import "reflect-metadata";
- You may also need to install
node typings( To useNodeSmart tips for ):npm install @types/node –save
- Install database driver
MySQLnpm install mysql --save( You can also installmysql2)
- Besides , Please make sure you are using
TypeScriptCompiler Version2.3Or later , And already intsconfig.jsonThe following settings are enabled in :"emitDecoratorMetadata": true,"experimentalDecorators": true,
- You may also need to add the compiler options in the lib Enable es , Or from
@typesinstalles6-shim
install ( Two )
Start using
TypeORMThe quickest way to do this is to use itsCLIcommand ( The scaffold ) Build startup project . Only inNodeJSUsed in applicationsTypeORMwhen , This operation is effective .First, install it globally
TypeORM:npm install typeorm –g
Then go to the directory where you want to create the new project and run the command :
typeorm init --name LearnTypeorm --database mysql
among
nameIs the name of the project ,databaseIs the database you will use .- The database can be one of the following values :
mysql, mariadb, postgres, sqlite, mssql, oracle, mongodb, cordova, react-native, expo, nativescript. - You can also use existing
nodeRunning on the projecttypeorm init, But should pay attention to , This operation may overwrite some existing files .
- The database can be one of the following values :
Then open the created project with the editing software , One will appear first
mdDocumentation
First step :
npm i
The second step : Delete
srcUnder the foldermigrationfileThe third step : To configure
tsconfig.jsonfile ( hold"module":"ESNext"Switch to"module": "CommonJS")
Step four : To configure
ormconfig.json
{ "type": "mysql", "host": "localhost", "port": 3306, "username": "root", "password": "123456", "database": "mall", "synchronize": true, "logging": false, "entities": [ "src/entity/**/*.ts" ], "cli": { "entitiesDir": "src/entity" } }
Package dependency (package.json)
Note that version : If an error occurs in the execution of the following file , Maybe your package version is too high
{ "name": "learn_typeorm", "version": "0.0.1", "description": "Awesome project developed with TypeORM.", "devDependencies": { "ts-node": "3.3.0", "@types/node": "^8.0.29", "typescript": "3.3.3333" }, "dependencies": { "mysql": "^2.14.1", "reflect-metadata": "^0.1.10", "ts-node-dev": "^1.1.8", "typeorm": "0.2.37" }, "scripts": { "start": "ts-node-dev src/find advanced options .ts" } }
Database configuration file
- Most of the time , We want to store the connection options in a separate configuration file , Because this way makes management more convenient and easy .
TypeORMSupport multiple configuration sources . You just need to be in the root directory of the application (package.jsonnear ) Create aormconfig.[format]File storage connection configuration , And call... In the applicationcreateConnection(), Without passing any parameter configuration - Supported by
ormconfigThe file format is :.json,.js,.env,.ymland.xml
Typeorm Which profile to use
- Sometimes you may want to use multiple configurations in different formats . When calling
getConnectionOptions()Or try using... Without the connection optioncreateConnection()when ,TypeormWill attempt to load the configuration in the following order : - From the other
ormconfig.[format]file , In this order :[js,ts,json,yml,yaml,xml]. - Be careful ,
TypeormThe first effective method found will be used , Instead of loading other methods . for example , If the configuration is found in the environment ,TypeormWill not loadormconfig.[format]file .
ConnectionOptions( One )
- The connection option is what you pass to
createConnectionOr in theormconfigConnection configuration defined in the file . Different databases have their own specific connection options . - Common connection options :
type- Database type . You must specify the database engine to use . The value can be "mysql....". This option is required .name- Connection name . In the use ofgetConnection(name: string)orConnectionManager.get(name: string)You need to use . The connection names of different connections cannot be the same , They must all be unique . If no connection name is given , Then it will be set to "default".entities- The entity to load and use for this connection . Accept the entity class and directory path to load . Directory Support glob Pattern . Example :entities: [Post, Category, "entity/*.js", "modules/**/entity/*.js"].subscribers- Subscribers to load and use for this connection . Accept the entity classes and directories to load .migrations- To load and migrate for this connection . Accept the migration classes and directories to loadlogging- Indicates whether logging is enabled . If set totrue, Query and error logging will be enabled . You can also specify different types of logging to enable , for example["query", "error", "schema"]
ConnectionOptions( Two )
maxQueryExecutionTime- If the query execution time exceeds the given maximum execution time ( In Milliseconds ), be logger This query will be logged .entityPrefix- To all tables on this database connection ( Or set ) Prefix added .dropSchema- Delete the schema every time a connection is established . Note this option , Don't use it in a production environment , Otherwise, all production data will be lost . But this option is very useful during debugging and development .synchronize- Indicates whether the database schema is automatically created every time the application starts . Note this option , Don't use it in a production environment , Otherwise, all production data will be lost . But this option is very useful during debugging and development .cache- Enable entity result caching .cli.entitiesDir-CLIBy default, create the directory of entities .cli.migrationsDir-CLICreate the migrated directory by default .cli.subscribersDir-CLICreate a directory for subscribers by default .
Connect Connection
from
ormconfigFile load all connection optionsimport 'reflect-metadata' import { createConnection} from "typeorm"; import { User} from "./entity/User"; const getConnection = async ()=>{ // Create database connection const connection = await createConnection() console.log(connection) } getConnection()
Use EntityManager
RepositoryIt's likeEntityManagerequally , But its operation is limited to specific entities .// User.ts import { Entity, PrimaryGeneratedColumn, Column } from "typeorm" @Entity() export class User { @PrimaryGeneratedColumn() id: number @Column() firstName: string @Column() lastName: string @Column() age: number // Constructors constructor(firstName: string, lastName: string, age: number,id?:number) { this.firstName = firstName; this.lastName = lastName; this.age = age; this.id = id } }// index.ts import 'reflect-metadata' import { createConnection, getManager} from "typeorm"; import { User} from "./entity/User"; createConnection().then(()=>{ // Get entity manager const entityManger = getManager() /** * add to */ const save = async ()=>{ const user:User = new User(' Zhang ',' 3、 ... and ',20) // Add users through entity manager const res = await entityManger.save<User>(user) console.log(res) } // save() /** * Query all */ const queryAll = async ()=>{ // Query all const [users]:User[] = await entityManger.find<User>(User) console.log(users) } // queryAll() /** * modify */ const edit = async () => { const user:User = new User(' Li ',' Four ',20,1) const res = await entityManger.save<User>(user) console.log(res) } // edit() /** * Delete */ const del = async ()=>{ const { affected} = await entityManger.delete<User>(User,[3,4]) console.log(affected?' Delete successful ':' Delete failed ') } // del() })
Use Repository
RepositoryIt's likeEntityManagerequally , But its operation is limited to specific entities .// User.ts import { Entity, PrimaryGeneratedColumn, Column } from "typeorm" @Entity() export class User { @PrimaryGeneratedColumn() id: number @Column() firstName: string @Column() lastName: string @Column() age: number // Constructors constructor(firstName: string, lastName: string, age: number,id?:number) { this.firstName = firstName; this.lastName = lastName; this.age = age; this.id = id } }// index.ts import 'reflect-metadata' import { createConnection, getRepository} from "typeorm"; import { User} from "./entity/User"; /** * Repository */ createConnection().then((connection)=>{ // Get repository const userRepository = getRepository(User) /** * add to */ const save = async ()=>{ const user:User = new User(' Liu ',' can ',30) const res = await userRepository.save(user) console.log(res) } // save() /** * Query all */ const queryAll = async ()=>{ const users:User[] = await userRepository.find() console.log(users) } // queryAll() /** * modify */ const edit = async () => { const user:User = new User(' Liu ',' can ',11,7) const res = await userRepository.save(user) console.log(res) } // edit() /** * Delete */ const del = async ()=>{ const { affected} = await userRepository.delete(5) console.log(affected?' Delete successful ':' Delete failed ') } del() })
Custom Repository
You can create a custom repository , It should include methods for using the database . You typically create custom repositories for individual entities , And include its specific queries
import "reflect-metadata"; // Using the decorator requires importing import { EntityRepository, Repository, getCustomRepository, createConnection} from 'typeorm'; import { User} from "./entity/User"; // Decorator Custom user storage inventory Repository @EntityRepository(User) class UserRepository extends Repository<User>{ // Custom methods findByName(firstName: string, lastName: string) { return this.findOne({ firstName,lastName}) } } createConnection().then(()=>{ // Get an instance of the custom Repository Parameters are custom repositories const userRepository= getCustomRepository(UserRepository) // const save = async()=>{ // const user:User = new User(' king ',' 5、 ... and ',18) // const res = await userRepository.save(user) // console.log(res) // } // save() const queryByName = async ()=>{ const user = await userRepository.findByName(' king ',' 5、 ... and ') console.log(user) } queryByName() })
Find Options - Basic options
All repositories and managers
findMethods accept special options that can be used to query the required data , Without having to useQueryBuilder// index.ts import "reflect-metadata"; import { createConnection, getRepository} from "typeorm"; import { User} from "./entity/User"; // Using the decorator requires importing createConnection().then(async ()=>{ const userRepository = getRepository(User) const res = await userRepository.find({ // Limit query fields select:['id','firstName','lastName','age'], // Query criteria // where:{firstName:' Zhang '} // or Using arrays where:[{ firstName:' Zhang '},{ firstName: ' Liu '}], // order Sort // ASC 1 Ascending // DESC -1 Descending order:{ id:'DESC'}, // Pagination // skip The starting position skip:0, // take Number take:1, // Open cache or not cache:true }) console.log(res) })
Find Options - advanced options
TypeORMProvides many built-in operators , Can be used to create more complex queriesimport "reflect-metadata"; import { createConnection, getRepository, LessThan, LessThanOrEqual, Not, MoreThan, MoreThanOrEqual, Equal, Like, Between, In } from "typeorm"; import { User} from "./entity/User"; /** * find Options - Advanced */ // Create database connection createConnection().then(async()=> { // Get the user's Repository const userRepository = getRepository(User) // Not:SELECT * FROM "user" WHERE "firstName" != ' Zhang '; // user The table does not contain firstName by Zhang Of const users: User[] = await userRepository.find({ firstName:Not(' Zhang ') }) console.log(" List of no messages ",users) // LessThan:SELECT * FROM "user" WHERE "age" < 15 // user In the table age Less than 15 A list of const users1: User[] = await userRepository.find({ age:LessThan(15) }) console.log(" Age is less than 15 A list of ",users1) // LessThanOrEqual:SELECT * FROM "user" WHERE "age" <= 11 // user In the table age Less than or equal to 11 A list of const users2: User[] = await userRepository.find({ age:LessThanOrEqual (11) }) console.log(" The age is less than or equal to 11 A list of ",users2) // MoreThan:SELECT * FROM "user" WHERE "age" > 10 // user In the table age Greater than 10 A list of const users3: User[] = await userRepository.find({ age:MoreThan (10) }) console.log(" Older than 10 A list of ",users3) // MoreThanOrEqual: SELECT * FROM "user" WHERE "age" > = 20 // user In the table age Greater than or equal to 20 A list of const users4: User[] = await userRepository.find({ age:MoreThanOrEqual (20) }) console.log(" Older than or equal to 20 A list of ",users4) // Equal: SELECT * FROM "user" WHERE "age" = 11 // user In the table age Greater than or equal to 20 A list of const users5: User[] = await userRepository.find({ age:Equal (11) }) console.log(" Age equals 11 A list of ",users5) // Like:SELECT * FROM "user" WHERE "firstName" LIKE '% Zhang %' // Fuzzy query user In the table firstName surname Zhang A list of const users6: User[] = await userRepository.find({ firstName:Like ('% Zhang %') }) console.log(" Fuzzy query the list of surnames Zhang ",users6) // Between:SELECT * FROM "user" WHERE "age" BETWEEN 1 AND 10 // Inquire about user In the table age stay 1 To 11 Between Include 1 and 11 const users7: User[] = await userRepository.find({ age:Between (1,11) }) console.log(" Check age 1 To 11 Between ",users7) // In: SELECT * FROM "user" WHERE "age" IN (11,20) // Inquire about user In the table age stay 11 and 20 const users8: User[] = await userRepository.find({ age:In([11,20]) }) console.log(users8) })
Entity
Entity : Is a class that maps to database tables . You can create an entity by defining a new class , And use
@Entity()To markEntity Columns : Because the database table consists of columns , So entities must also consist of columns . Be marked with
@ColumnEach entity class attribute of will be mapped to the database table columnMain column : Each entity must have at least one primary column . There are several types of main columns :
@PrimaryColumn()Create a primary column , It can get any value of any type . You can also specify the column type . If no column type is specified , Will be automatically inferred from the attribute type .@PrimaryGeneratedColumn()Create a primary column , This value is automatically generated using the auto increment value .@PrimaryGeneratedColumn("uuid")Create a primary column , This value will useuuidAutomatic generation ,(UuidIs a unique stringid)
Special column :
@CreateDateColumnAutomatically insert date for entity . There is no need to set this column , This value will be set automatically .@UpdateDateColumnEvery time the entity manager or repository is calledsavewhen , Automatically update entity date . There is no need to set this column , This value will be set automatically .
Column type
@Column(“int”)perhaps@Column({ type: "int" })- If you want to specify other type parameters , You can perform... Through column options : Example :
@Column("varchar", { length: 200 })
import { Column, CreateDateColumn, Entity, PrimaryGeneratedColumn, UpdateDateColumn} from "typeorm"; /** * Entity class => Database table * Added @Entity The decorator will be typeorm Demapping , Determine if the table exists , No tables will be created , There is no treatment * If you want to create a table structure of a class , You need to create @Entity() */ @Entity() export default class Person { // Primary key :PrimaryColumn // @PrimaryGeneratedColumn('uuid') Pass in uuid It will generate automatically uuid A primary key // Auto growing primary key @PrimaryGeneratedColumn() id:number // Automatically add creation time @CreateDateColumn() createAt:Date // Automatically modify the time @UpdateDateColumn() updateAt:Date // Column name varchar(255) // Added @Column() Will be mapped to fields in the table // You can specify the type of column You can also limit the length @Column('varchar',{ length:20}) name:string // You can specify the type of column @Column('int') gander:number constructor(name: string) { this.name = name; } }
mysql Column type for ( One )
int, tinyint, smallint, mediumint, bigint, float, double, dec, decimal, numeric, date, datetime, timestamp, time, year, char, varchar, nvarchar, text, tinytext, mediumtext, blob, longtext, tinyblob, mediumblob, longblob, enum, json, binary, geometry, point, linestring, polygon, multipoint, multilinestring, multipolygon, geometrycollectionenumColumn typeimport { Column, CreateDateColumn, Entity, PrimaryGeneratedColumn, UpdateDateColumn} from "typeorm"; export enum PersonRole { STUDENT = 'student', TEACHER = 'teacher' } /** * Entity class => Database table * Added @Entity The decorator will be typeorm Demapping , Determine if the table exists , No tables will be created , There is no treatment * If you want to create a table structure of a class , You need to create @Entity() */ @Entity() export default class Person { // Primary key :PrimaryColumn // @PrimaryGeneratedColumn('uuid') Pass in uuid It will generate automatically uuid A primary key // Auto growing primary key @PrimaryGeneratedColumn() id:number // Automatically add creation time @CreateDateColumn() createAt:Date // Automatically modify the time @UpdateDateColumn() updateAt:Date // Column name varchar(255) // Added @Column() Will be mapped to fields in the table // You can specify the type of column You can also limit the length @Column('varchar',{ length:20}) name:string // You can specify the type of column @Column('int') gander:number @Column({ type:"enum", enum:PersonRole }) role:PersonRole constructor(name: string, gander: number, role: PersonRole) { this.name = name; this.gander = gander; this.role = role; } }simple-arrayColumn type for : It can store the original array values in a single string column . All values are separated by commas . return , Will also be returned as an arrayimport { Column, CreateDateColumn, Entity, PrimaryGeneratedColumn, UpdateDateColumn} from "typeorm"; export enum PersonRole { STUDENT = 'student', TEACHER = 'teacher' } /** * Entity class => Database table * Added @Entity The decorator will be typeorm Demapping , Determine if the table exists , No tables will be created , There is no treatment * If you want to create a table structure of a class , You need to create @Entity() */ @Entity() export default class Person { // Primary key :PrimaryColumn // @PrimaryGeneratedColumn('uuid') Pass in uuid It will generate automatically uuid A primary key // Auto growing primary key @PrimaryGeneratedColumn() id:number // Automatically add creation time @CreateDateColumn() createAt:Date // Automatically modify the time @UpdateDateColumn() updateAt:Date // Column name varchar(255) // Added @Column() Will be mapped to fields in the table // You can specify the type of column You can also limit the length @Column('varchar',{ length:20}) name:string // You can specify the type of column @Column('int') gander:number @Column({ type:"enum", enum:PersonRole }) role:PersonRole @Column({ // A column is an array type:'simple-array' }) nickName:Array<string> constructor(name: string, gander: number, role: PersonRole) { this.name = name; this.gander = gander; this.role = role; } }
mysql Column type for ( Two )
simple-jsonColumn type : Can store anything that can be passedJSON.stringifyValues stored in the database . When there is nojsonType and you want to store and load objects , This type is usefulimport { Column, CreateDateColumn, Entity, PrimaryGeneratedColumn, UpdateDateColumn} from "typeorm"; export enum PersonRole { STUDENT = 'student', TEACHER = 'teacher' } /** * Entity class => Database table * Added @Entity The decorator will be typeorm Demapping , Determine if the table exists , No tables will be created , There is no treatment * If you want to create a table structure of a class , You need to create @Entity() */ @Entity() export default class Person { // Primary key :PrimaryColumn // @PrimaryGeneratedColumn('uuid') Pass in uuid It will generate automatically uuid A primary key // Auto growing primary key @PrimaryGeneratedColumn() id:number // Automatically add creation time @CreateDateColumn() createAt:Date // Automatically modify the time @UpdateDateColumn() updateAt:Date // Column name varchar(255) // Added @Column() Will be mapped to fields in the table // You can specify the type of column You can also limit the length @Column('varchar',{ length:20}) name:string // You can specify the type of column @Column('int') gander:number @Column({ type:"enum", enum:PersonRole }) role:PersonRole @Column({ // A column is an array type:'simple-array' }) nickName:Array<string> @Column('simple-json') perfile:{ name:string,nickName:string} constructor(name: string, gander: number, role: PersonRole) { this.name = name; this.gander = gander; this.role = role; } }
Column options
Column options define other options for entity columns . You can
@ColumnSpecify column options on :ColumnOptionsList of options available in :type: ColumnType- Column type .name: string- Column names in database tables . By default , The column name is generated from the name of the attribute . You can also change it by specifying your own name .length: number- Length of column type . for example , If you want to createvarchar(150)type , Please specify the column type and length options .nullable: boolean- Make Columns... In the databaseNULLorNOT NULL. By default , The column isnullable:false.update: boolean- instructions"save"Whether the operation updates the column value . Iffalse, The value can only be written when the object is first inserted . The default value is"true".select: boolean- Defines whether to hide this column by default when querying . Set tofalsewhen , Column data does not display standard queries . By default , The column isselect:truedefault: string- Add database level columnsDEFAULTvalue .primary: boolean- Mark the column as the primary column . Usage and@PrimaryColumnidentical .unique: boolean- Mark the column as unique ( Create a unique constraint ).comment: string- Database column comments , Not all database types support .enum: string[]|AnyEnum- stayenumUsed in column types , To specify a list of allowed enumeration values . You can also specify an array or an enumeration class .import { Column, Entity, PrimaryGeneratedColumn} from "typeorm"; @Entity() export class Student { @PrimaryGeneratedColumn() id:number @Column({ // Type of custom field type:'varchar', // The name of the custom field name:'sname', // Length of custom field length:20, // not null Allow null false Not empty nullable:true, update:true, // false Query does not show select:false, // Default value of column default:'123', // Unique constraint unique:false, // Column comment comment:' full name ', }) name:string constructor(name: string) { this.name = name; } }import 'reflect-metadata' import { createConnection, getRepository} from "typeorm"; import { Student} from "./entity/Student"; createConnection().then(async ()=>{ const studentRepository = getRepository(Student) // add to const stu = new Student(' Zhang San ') await studentRepository.save(stu) // Inquire about const student:Student[] = await studentRepository.find() console.log(student) })
Embed entity classes
- By using
embedded columns, It can reduce repetition in applications - An embedded column is a column , It accepts classes with its own columns , And merge these columns into the database table of the current entity .
Relationship
- What is relationship
- Relationships can help you easily work with related entities . There are several types of relationships
- one-on-one Use
@OneToOne - For one more Use
@ManyToOne - One to many Use
@OneToMany - Many to many Use
@ManyToMany
- one-on-one Use
- Relational options
eager: boolean- If set totrue, Then usefind *orQueryBuilderwhen , The primary entity will always be used to load the relationshipcascade: boolean- If set totrue, The related objects will be inserted and updated in the database .onDelete: "RESTRICT"|"CASCADE"|"SET NULL"- Specify how foreign keys behave when deleting referenced objectsprimary: boolean- Indicates whether the column of this relationship is the primary column .nullable: boolean- Indicates whether the columns of this relationship can be empty . It is nullable by default .orphanedRowAction: "nullify" | "delete"- After deleting a child row from its parent row , Confirm that the child row is orphaned ( The default value is ) Or deleted .
One-to-one relationship ( One )
One on one is a kind of
AContains only oneBexample , andBContains only oneAThe relationship of examples . We useUsersandProfileEntity as an example .Users can only have one profile , And a profile is owned by only one user .
// Profile.ts import { Column, Entity, PrimaryGeneratedColumn} from "typeorm"; @Entity() export class Profile { @PrimaryGeneratedColumn() id:number @Column() gander:number constructor(gander: number) { this.gander = gander; } }// Users.ts import { Column, Entity, JoinColumn, OneToOne, PrimaryGeneratedColumn} from "typeorm"; import { Profile} from "./Profile"; @Entity() export class Users { @PrimaryGeneratedColumn() id:number @Column() name:string // OneToOne one-on-one Specify the relationship @OneToOne(()=>Profile) // Foreign keys @JoinColumn() profile:Profile constructor(name: string, profile: Profile) { this.name = name; this.profile = profile; } }Here we will
@OneToOneAdd toprofileAnd specify the target relationship type asProfile. We also added@JoinColumn, This is required and can only be set on one side of the relationship . You set up@JoinColumnWhich side , Which side of the table will contain a "relation id" And the foreign key of the target entity table .
One-to-one relationship ( Two )
Again ,
@JoinColumnMust be set only on one side of the relationship and must have a foreign key on the side of the database table .// one-on-one .ts import { createConnection, getRepository} from "typeorm"; import { Profile} from "./entity/Profile"; import { Users} from "./entity/Users"; createConnection().then(()=>{ const usersRepository = getRepository(Users) const profileRepository = getRepository(Profile) const save = async ()=>{ // establish profile object const profile = new Profile(20) // add to profile Information to database await profileRepository.save(profile) // establish users object const users = new Users(' Zhang San ',profile) // add to users Information to database const res = await usersRepository.save(users) console.log(res) } // save() // Inquire about const queryOne = async () =>{ const users = await usersRepository.findOne({ relations:['profile'], where:{ id:1} }) console.log(users) } queryOne() })
For one more / One to many relationship ( One )
For one more / One to manyRefer toAContains multipleBThe relationship of examples , butBContains only oneAexample . Let's takeUserandPhotoEntity as an example .UserYou can have multiplephotos, But eachphotoBy only one personuserHave// Photo.ts import { Column, Entity, ManyToOne, PrimaryGeneratedColumn} from "typeorm"; import { User} from "./User"; @Entity() export class Photo{ @PrimaryGeneratedColumn() id:number @Column() url:string @ManyToOne(()=>User,person =>person.photos) person:User constructor(url: string) { this.url = url; } }// User.ts import { Column, Entity, OneToMany, PrimaryGeneratedColumn} from "typeorm"; import { Photo} from "./Photo"; @Entity() export class User { @PrimaryGeneratedColumn() id:number @OneToMany(()=>Photo,photo=> photo.person) photos:Photo[] constructor(photos: Photo[]) { this.photos = photos; } }Here we will
@OneToManyAdd tophotosProperties of the , And specify the target relationship type asPhoto. You can@ManyToOne / @OneToManyOmit@JoinColumn, Unless you need to customize the name of the associated column in the database .@ManyToOneCan be used alone , but@OneToManyIt has to go with@ManyToOneUse . If you want to use@OneToMany, You need to@ManyToOne. Before you set up@ManyToOneThe place of , Related entities will have" relation id"andForeign keys.
For one more / One to many relationship ( Two )
You need to query with
photosOfuser, Must be inFindOptionsSpecify the relationship inimport { createConnection, getRepository} from "typeorm"; import { User} from "./entity/User"; import { Photo} from "./entity/Photo"; createConnection().then(()=>{ const userRepository = getRepository(User) const photoRepository = getRepository(Photo) const save = async () => { const photo1 = new Photo('./img/01.jpg') const photo2 = new Photo('./img/02.jpg') await photoRepository.save([photo1,photo2]) const user = new User([photo1,photo2]) const res = await userRepository.save(user) console.log(res) } // save() const queryAll = async () =>{ const res = await userRepository.find({ relations:['photos'] }) console.log(res) } queryAll() })
many-to-many ( One )
Many to many is a kind of
AContains multipleBexample , andBContains multipleAThe relationship of examples . We useQuestionandCategoryEntity as an example .QuestionThere can be multiplecategories, EverycategoryThere can be multiplequestions// Category Category import { Column, Entity, PrimaryGeneratedColumn} from "typeorm"; @Entity() export class Category { @PrimaryGeneratedColumn() id:number @Column() name:string constructor(name: string) { this.name = name; } }// Question problem import { Column, Entity, JoinTable, ManyToMany, PrimaryGeneratedColumn} from "typeorm"; import { Category} from "./Category"; @Entity() export class Question { @PrimaryGeneratedColumn() id:number @Column() title:string @Column() text:string @ManyToMany(()=>Category) @JoinTable() categories:Category[] constructor(title: string, text: string, categories: Category[]) { this.title = title; this.text = text; this.categories = categories; } }@JoinTable()yes@ManyToManyNecessary for a relationship
many-to-many ( Two )
To be in
categoriesLoading insidequestion, You must be there.FindOptionsSpecify the relationship inimport { createConnection, getRepository} from "typeorm"; import { Category} from "./entity/Category"; import { Question} from "./entity/Question"; createConnection().then(()=>{ const categoryRepository = getRepository(Category) const questionRepository = getRepository(Question) const save = async () =>{ const category1 = new Category('animals') const category2 = new Category('zoo ') await categoryRepository.save([category1,category2]) const question = new Question(' title ',' Text ',[category1,category2]) const res = await questionRepository.save(question) console.log(res) } // save() const queryAll = async ()=>{ const res = await questionRepository.find({ relations:['categories'] }) console.log(res) } queryAll() })
Use Query Builder
QueryBuilderyesTypeORMOne of the most powerful features , It allows you to build with elegant and convenient syntaxSQLInquire about , Execute and get automatically transformed entities .
Reverse generate database model
- First, install it globally :
npm install typeorm-model-generator - Then reverse generate the code :
typeorm-model-generator -h localhost -d mall -u root -x 123456 -e mysql -o entity-h localhost -d Database name -p port -u user name -x password -e Database type-o entitiesIndicates output to the specified folder
边栏推荐
- What can the points mall Games bring to businesses? How to build a points mall?
- Summary of spanner's paper
- Unity项目心得总结
- Actual combat: gateway api-2022.2.13
- 工业导电滑环的应用
- AcWing 884. Gauss elimination for solving XOR linear equations
- 液压滑环的特点讲解
- tar命令
- Introduction to 3D modeling and processing software Liu Ligang University of science and technology of China
- Use and principle of Park unpark
猜你喜欢

Application and principle of ThreadPoolExecutor thread pool

Unity项目心得总结

C# wpf 使用DockPanel实现截屏框

Lock free concurrency of JUC (leguan lock)

Actual combat: gateway api-2022.2.13

提高企业产品交付效率系列(1)—— 企业应用一键安装和升级

Usage and principle of synchronized

Redis数据库的部署及常用命令

Using nocalhost to develop microservice application on rainbow
![Solution: thread 1:[< *> setvalue:forundefined key]: this class is not key value coding compliant for the key*](/img/88/0b99d1db2cdc70ab72d2b3c623dfaa.jpg)
Solution: thread 1:[< *> setvalue:forundefined key]: this class is not key value coding compliant for the key*
随机推荐
Use and principle of reentrantlock
Day 05 - file operation function
Flutter can refresh data every time the interface comes in
Using nocalhost to develop microservice application on rainbow
Software intelligence: the "world" and "boundary" of AI sentient beings in AAAs system
HCIP Day13
Rust基础入门之变量绑定与解构
Rainbond结合NeuVector实践容器安全管理
What can the points mall Games bring to businesses? How to build a points mall?
Go learning notes (5) basic types and declarations (4)
AcWing 884. Gauss elimination for solving XOR linear equations
Global and Chinese market of solder wire 2022-2028: Research Report on technology, participants, trends, market size and share
Application of industrial conductive slip ring
el-cascader回显失败;el-cascader回显不出来
Distributed transactions - Solutions
Rust hello-word
Lock free concurrency of JUC (leguan lock)
LRU cache for leveldb source code analysis
Global and Chinese market of paper machine systems 2022-2028: Research Report on technology, participants, trends, market size and share
C# wpf 使用DockPanel实现截屏框