当前位置:   article > 正文

TypeORM的官方文档(转发)_typeorm文档

typeorm文档

最近在学习node的相关东西,前端操作数据库看到了TypeORM,这个是中文文档https://typeorm.bootcss.com/,也在B站上看了几十分钟的视频,还是很容易理解的。但是中文文档落后了英文文档的很多版本,还是fork到自己的git,阅读英文文档。

注:公司网络访问github不稳定,转载出来,便于阅读。

  1. TypeORM is an [ORM](https://en.wikipedia.org/wiki/Object-relational_mapping)
  2. that can run in NodeJS, Browser, Cordova, PhoneGap, Ionic, React Native, NativeScript, Expo, and Electron platforms
  3. and can be used with TypeScript and JavaScript (ES5, ES6, ES7, ES8).
  4. Its goal is to always support the latest JavaScript features and provide additional features
  5. that help you to develop any kind of application that uses databases - from
  6. small applications with a few tables to large scale enterprise applications
  7. with multiple databases.
  8. TypeORM supports both [Active Record](./docs/active-record-data-mapper.md#what-is-the-active-record-pattern) and [Data Mapper](./docs/active-record-data-mapper.md#what-is-the-data-mapper-pattern) patterns,
  9. unlike all other JavaScript ORMs currently in existence,
  10. which means you can write high quality, loosely coupled, scalable,
  11. maintainable applications the most productive way.
  12. TypeORM is highly influenced by other ORMs, such as [Hibernate](http://hibernate.org/orm/),
  13. [Doctrine](http://www.doctrine-project.org/) and [Entity Framework](https://www.asp.net/entity-framework).
  14. ## Features
  15. - Supports both [DataMapper](./docs/active-record-data-mapper.md#what-is-the-data-mapper-pattern) and [ActiveRecord](./docs/active-record-data-mapper.md#what-is-the-active-record-pattern) (your choice).
  16. - Entities and columns.
  17. - Database-specific column types.
  18. - Entity manager.
  19. - Repositories and custom repositories.
  20. - Clean object relational model.
  21. - Associations (relations).
  22. - Eager and lazy relations.
  23. - Uni-directional, bi-directional and self-referenced relations.
  24. - Supports multiple inheritance patterns.
  25. - Cascades.
  26. - Indices.
  27. - Transactions.
  28. - Migrations and automatic migrations generation.
  29. - Connection pooling.
  30. - Replication.
  31. - Using multiple database instances.
  32. - Working with multiple databases types.
  33. - Cross-database and cross-schema queries.
  34. - Elegant-syntax, flexible and powerful QueryBuilder.
  35. - Left and inner joins.
  36. - Proper pagination for queries using joins.
  37. - Query caching.
  38. - Streaming raw results.
  39. - Logging.
  40. - Listeners and subscribers (hooks).
  41. - Supports closure table pattern.
  42. - Schema declaration in models or separate configuration files.
  43. - Connection configuration in json / xml / yml / env formats.
  44. - Supports MySQL / MariaDB / Postgres / CockroachDB / SQLite / Microsoft SQL Server / Oracle / SAP Hana / sql.js.
  45. - Supports MongoDB NoSQL database.
  46. - Works in NodeJS / Browser / Ionic / Cordova / React Native / NativeScript / Expo / Electron platforms.
  47. - TypeScript and JavaScript support.
  48. - ESM and CommonJS support.
  49. - Produced code is performant, flexible, clean and maintainable.
  50. - Follows all possible best practices.
  51. - CLI.
  52. And more...
  53. With TypeORM your models look like this:
  54. ```typescript
  55. import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"
  56. @Entity()
  57. export class User {
  58. @PrimaryGeneratedColumn()
  59. id: number
  60. @Column()
  61. firstName: string
  62. @Column()
  63. lastName: string
  64. @Column()
  65. age: number
  66. }
  67. ```
  68. And your domain logic looks like this:
  69. ```typescript
  70. const userRepository = MyDataSource.getRepository(User)
  71. const user = new User()
  72. user.firstName = "Timber"
  73. user.lastName = "Saw"
  74. user.age = 25
  75. await userRepository.save(user)
  76. const allUsers = await userRepository.find()
  77. const firstUser = await userRepository.findOneBy({
  78. id: 1,
  79. }) // find by id
  80. const timber = await userRepository.findOneBy({
  81. firstName: "Timber",
  82. lastName: "Saw",
  83. }) // find by firstName and lastName
  84. await userRepository.remove(timber)
  85. ```
  86. Alternatively, if you prefer to use the `ActiveRecord` implementation, you can use it as well:
  87. ```typescript
  88. import { Entity, PrimaryGeneratedColumn, Column, BaseEntity } from "typeorm"
  89. @Entity()
  90. export class User extends BaseEntity {
  91. @PrimaryGeneratedColumn()
  92. id: number
  93. @Column()
  94. firstName: string
  95. @Column()
  96. lastName: string
  97. @Column()
  98. age: number
  99. }
  100. ```
  101. And your domain logic will look this way:
  102. ```typescript
  103. const user = new User()
  104. user.firstName = "Timber"
  105. user.lastName = "Saw"
  106. user.age = 25
  107. await user.save()
  108. const allUsers = await User.find()
  109. const firstUser = await User.findOneBy({
  110. id: 1,
  111. })
  112. const timber = await User.findOneBy({
  113. firstName: "Timber",
  114. lastName: "Saw"
  115. })
  116. await timber.remove()
  117. ```
  118. ## Installation
  119. 1. Install the npm package:
  120. `npm install typeorm --save`
  121. 2. You need to install `reflect-metadata` shim:
  122. `npm install reflect-metadata --save`
  123. and import it somewhere in the global place of your app (for example in `app.ts`):
  124. `import "reflect-metadata"`
  125. 3. You may need to install node typings:
  126. `npm install @types/node --save-dev`
  127. 4. Install a database driver:
  128. - for **MySQL** or **MariaDB**
  129. `npm install mysql --save` (you can install `mysql2` instead as well)
  130. - for **PostgreSQL** or **CockroachDB**
  131. `npm install pg --save`
  132. - for **SQLite**
  133. `npm install sqlite3 --save`
  134. - for **Microsoft SQL Server**
  135. `npm install mssql --save`
  136. - for **sql.js**
  137. `npm install sql.js --save`
  138. - for **Oracle**
  139. `npm install oracledb --save`
  140. To make the Oracle driver work, you need to follow the installation instructions from
  141. [their](https://github.com/oracle/node-oracledb) site.
  142. - for **SAP Hana**
  143. ```
  144. npm install @sap/hana-client
  145. npm install hdb-pool
  146. ```
  147. _SAP Hana support made possible by the sponsorship of [Neptune Software](https://www.neptune-software.com/)._
  148. - for **Google Cloud Spanner**
  149. ```
  150. npm install @google-cloud/spanner --save
  151. ```
  152. Provide authentication credentials to your application code
  153. by setting the environment variable `GOOGLE_APPLICATION_CREDENTIALS`:
  154. ```shell
  155. # Linux/macOS
  156. export GOOGLE_APPLICATION_CREDENTIALS="KEY_PATH"
  157. # Windows
  158. set GOOGLE_APPLICATION_CREDENTIALS=KEY_PATH
  159. # Replace KEY_PATH with the path of the JSON file that contains your service account key.
  160. ```
  161. To use Spanner with the emulator you should set `SPANNER_EMULATOR_HOST` environment variable:
  162. ```shell
  163. # Linux/macOS
  164. export SPANNER_EMULATOR_HOST=localhost:9010
  165. # Windows
  166. set SPANNER_EMULATOR_HOST=localhost:9010
  167. ```
  168. - for **MongoDB** (experimental)
  169. `npm install mongodb@^3.6.0 --save`
  170. - for **NativeScript**, **react-native** and **Cordova**
  171. Check [documentation of supported platforms](./docs/supported-platforms.md)
  172. Install only _one_ of them, depending on which database you use.
  173. ##### TypeScript configuration
  174. Also, make sure you are using TypeScript version **4.5** or higher,
  175. and you have enabled the following settings in `tsconfig.json`:
  176. ```json
  177. "emitDecoratorMetadata": true,
  178. "experimentalDecorators": true,
  179. ```
  180. You may also need to enable `es6` in the `lib` section of compiler options, or install `es6-shim` from `@types`.
  181. ## Quick Start
  182. The quickest way to get started with TypeORM is to use its CLI commands to generate a starter project.
  183. Quick start works only if you are using TypeORM in a NodeJS application.
  184. If you are using other platforms, proceed to the [step-by-step guide](#step-by-step-guide).
  185. To create a new project using CLI, run the following command:
  186. ```shell
  187. npx typeorm init --name MyProject --database postgres
  188. ```
  189. Where `name` is the name of your project and `database` is the database you'll use.
  190. Database can be one of the following values: `mysql`, `mariadb`, `postgres`, `cockroachdb`, `sqlite`, `mssql`, `sap`, `spanner`, `oracle`, `mongodb`,
  191. `cordova`, `react-native`, `expo`, `nativescript`.
  192. This command will generate a new project in the `MyProject` directory with the following files:
  193. ```
  194. MyProject
  195. ├── src // place of your TypeScript code
  196. │ ├── entity // place where your entities (database models) are stored
  197. │ │ └── User.ts // sample entity
  198. │ ├── migration // place where your migrations are stored
  199. │ ├── data-source.ts // data source and all connection configuration
  200. │ └── index.ts // start point of your application
  201. ├── .gitignore // standard gitignore file
  202. ├── package.json // node module dependencies
  203. ├── README.md // simple readme file
  204. └── tsconfig.json // TypeScript compiler options
  205. ```
  206. > You can also run `typeorm init` on an existing node project, but be careful - it may override some files you already have.
  207. The next step is to install new project dependencies:
  208. ```shell
  209. cd MyProject
  210. npm install
  211. ```
  212. After you have all dependencies installed, edit the `data-source.ts` file and put your own database connection configuration options in there:
  213. ```ts
  214. export const AppDataSource = new DataSource({
  215. type: "postgres",
  216. host: "localhost",
  217. port: 5432,
  218. username: "test",
  219. password: "test",
  220. database: "test",
  221. synchronize: true,
  222. logging: true,
  223. entities: [Post, Category],
  224. subscribers: [],
  225. migrations: [],
  226. })
  227. ```
  228. Particularly, most of the time you'll only need to configure
  229. `host`, `username`, `password`, `database` and maybe `port` options.
  230. Once you finish with configuration and all node modules are installed, you can run your application:
  231. ```shell
  232. npm start
  233. ```
  234. That's it, your application should successfully run and insert a new user into the database.
  235. You can continue to work with this project and integrate other modules you need and start
  236. creating more entities.
  237. > You can generate an ESM project by running
  238. > `npx typeorm init --name MyProject --database postgres --module esm` command.
  239. > You can generate an even more advanced project with express installed by running
  240. > `npx typeorm init --name MyProject --database mysql --express` command.
  241. > You can generate a docker-compose file by running
  242. > `npx typeorm init --name MyProject --database postgres --docker` command.
  243. ## Step-by-Step Guide
  244. What are you expecting from ORM?
  245. First of all, you are expecting it will create database tables for you
  246. and find / insert / update / delete your data without the pain of
  247. having to write lots of hardly maintainable SQL queries.
  248. This guide will show you how to set up TypeORM from scratch and make it do what you are expecting from an ORM.
  249. ### Create a model
  250. Working with a database starts from creating tables.
  251. How do you tell TypeORM to create a database table?
  252. The answer is - through the models.
  253. Your models in your app are your database tables.
  254. For example, you have a `Photo` model:
  255. ```typescript
  256. export class Photo {
  257. id: number
  258. name: string
  259. description: string
  260. filename: string
  261. views: number
  262. isPublished: boolean
  263. }
  264. ```
  265. And you want to store photos in your database.
  266. To store things in the database, first, you need a database table,
  267. and database tables are created from your models.
  268. Not all models, but only those you define as _entities_.
  269. ### Create an entity
  270. _Entity_ is your model decorated by an `@Entity` decorator.
  271. A database table will be created for such models.
  272. You work with entities everywhere in TypeORM.
  273. You can load/insert/update/remove and perform other operations with them.
  274. Let's make our `Photo` model an entity:
  275. ```typescript
  276. import { Entity } from "typeorm"
  277. @Entity()
  278. export class Photo {
  279. id: number
  280. name: string
  281. description: string
  282. filename: string
  283. views: number
  284. isPublished: boolean
  285. }
  286. ```
  287. Now, a database table will be created for the `Photo` entity and we'll be able to work with it anywhere in our app.
  288. We have created a database table, however, what table can exist without columns?
  289. Let's create few columns in our database table.
  290. ### Adding table columns
  291. To add database columns, you simply need to decorate an entity's properties you want to make into a column
  292. with a `@Column` decorator.
  293. ```typescript
  294. import { Entity, Column } from "typeorm"
  295. @Entity()
  296. export class Photo {
  297. @Column()
  298. id: number
  299. @Column()
  300. name: string
  301. @Column()
  302. description: string
  303. @Column()
  304. filename: string
  305. @Column()
  306. views: number
  307. @Column()
  308. isPublished: boolean
  309. }
  310. ```
  311. Now `id`, `name`, `description`, `filename`, `views` and `isPublished` columns will be added to the `photo` table.
  312. Column types in the database are inferred from the property types you used, e.g.
  313. `number` will be converted into `integer`, `string` into `varchar`, `boolean` into `bool`, etc.
  314. But you can use any column type your database supports by explicitly specifying a column type into the `@Column` decorator.
  315. We generated a database table with columns, but there is one thing left.
  316. Each database table must have a column with a primary key.
  317. ### Creating a primary column
  318. Each entity **must** have at least one primary key column.
  319. This is a requirement and you can't avoid it.
  320. To make a column a primary key, you need to use the `@PrimaryColumn` decorator.
  321. ```typescript
  322. import { Entity, Column, PrimaryColumn } from "typeorm"
  323. @Entity()
  324. export class Photo {
  325. @PrimaryColumn()
  326. id: number
  327. @Column()
  328. name: string
  329. @Column()
  330. description: string
  331. @Column()
  332. filename: string
  333. @Column()
  334. views: number
  335. @Column()
  336. isPublished: boolean
  337. }
  338. ```
  339. ### Creating an auto-generated column
  340. Now, let's say you want your id column to be auto-generated (this is known as auto-increment / sequence / serial / generated identity column).
  341. To do that, you need to change the `@PrimaryColumn` decorator to a `@PrimaryGeneratedColumn` decorator:
  342. ```typescript
  343. import { Entity, Column, PrimaryGeneratedColumn } from "typeorm"
  344. @Entity()
  345. export class Photo {
  346. @PrimaryGeneratedColumn()
  347. id: number
  348. @Column()
  349. name: string
  350. @Column()
  351. description: string
  352. @Column()
  353. filename: string
  354. @Column()
  355. views: number
  356. @Column()
  357. isPublished: boolean
  358. }
  359. ```
  360. ### Column data types
  361. Next, let's fix our data types. By default, the string is mapped to a varchar(255)-like type (depending on the database type).
  362. The number is mapped to an integer-like type (depending on the database type).
  363. We don't want all our columns to be limited varchars or integers.
  364. Let's setup correct data types:
  365. ```typescript
  366. import { Entity, Column, PrimaryGeneratedColumn } from "typeorm"
  367. @Entity()
  368. export class Photo {
  369. @PrimaryGeneratedColumn()
  370. id: number
  371. @Column({
  372. length: 100,
  373. })
  374. name: string
  375. @Column("text")
  376. description: string
  377. @Column()
  378. filename: string
  379. @Column("double")
  380. views: number
  381. @Column()
  382. isPublished: boolean
  383. }
  384. ```
  385. Column types are database-specific.
  386. You can set any column type your database supports.
  387. More information on supported column types can be found [here](./docs/entities.md#column-types).
  388. ### Creating a new `DataSource`
  389. Now, when our entity is created, let's create `index.ts` file and set up our `DataSource` there:
  390. ```typescript
  391. import "reflect-metadata"
  392. import { DataSource } from "typeorm"
  393. import { Photo } from "./entity/Photo"
  394. const AppDataSource = new DataSource({
  395. type: "postgres",
  396. host: "localhost",
  397. port: 5432,
  398. username: "root",
  399. password: "admin",
  400. database: "test",
  401. entities: [Photo],
  402. synchronize: true,
  403. logging: false,
  404. })
  405. // to initialize initial connection with the database, register all entities
  406. // and "synchronize" database schema, call "initialize()" method of a newly created database
  407. // once in your application bootstrap
  408. AppDataSource.initialize()
  409. .then(() => {
  410. // here you can start to work with your database
  411. })
  412. .catch((error) => console.log(error))
  413. ```
  414. We are using Postgres in this example, but you can use any other supported database.
  415. To use another database, simply change the `type` in the options to the database type you are using:
  416. `mysql`, `mariadb`, `postgres`, `cockroachdb`, `sqlite`, `mssql`, `oracle`, `sap`, `spanner`, `cordova`, `nativescript`, `react-native`,
  417. `expo`, or `mongodb`.
  418. Also make sure to use your own host, port, username, password and database settings.
  419. We added our Photo entity to the list of entities for this data source.
  420. Each entity you are using in your connection must be listed there.
  421. Setting `synchronize` makes sure your entities will be synced with the database, every time you run the application.
  422. ### Running the application
  423. Now if you run your `index.ts`, a connection with the database will be initialized and a database table for your photos will be created.
  424. ```shell
  425. +-------------+--------------+----------------------------+
  426. | photo |
  427. +-------------+--------------+----------------------------+
  428. | id | int(11) | PRIMARY KEY AUTO_INCREMENT |
  429. | name | varchar(100) | |
  430. | description | text | |
  431. | filename | varchar(255) | |
  432. | views | int(11) | |
  433. | isPublished | boolean | |
  434. +-------------+--------------+----------------------------+
  435. ```
  436. ### Creating and inserting a photo into the database
  437. Now let's create a new photo to save it in the database:
  438. ```typescript
  439. import { Photo } from "./entity/Photo"
  440. import { AppDataSource } from "./index"
  441. const photo = new Photo()
  442. photo.name = "Me and Bears"
  443. photo.description = "I am near polar bears"
  444. photo.filename = "photo-with-bears.jpg"
  445. photo.views = 1
  446. photo.isPublished = true
  447. await AppDataSource.manager.save(photo)
  448. console.log("Photo has been saved. Photo id is", photo.id)
  449. ```
  450. Once your entity is saved it will get a newly generated id.
  451. `save` method returns an instance of the same object you pass to it.
  452. It's not a new copy of the object, it modifies its "id" and returns it.
  453. ### Using Entity Manager
  454. We just created a new photo and saved it in the database.
  455. We used `EntityManager` to save it.
  456. Using entity manager you can manipulate any entity in your app.
  457. For example, let's load our saved entity:
  458. ```typescript
  459. import { Photo } from "./entity/Photo"
  460. import { AppDataSource } from "./index"
  461. const savedPhotos = await AppDataSource.manager.find(Photo)
  462. console.log("All photos from the db: ", savedPhotos)
  463. ```
  464. `savedPhotos` will be an array of Photo objects with the data loaded from the database.
  465. Learn more about EntityManager [here](./docs/working-with-entity-manager.md).
  466. ### Using Repositories
  467. Now let's refactor our code and use `Repository` instead of `EntityManager`.
  468. Each entity has its own repository which handles all operations with its entity.
  469. When you deal with entities a lot, Repositories are more convenient to use than EntityManagers:
  470. ```typescript
  471. import { Photo } from "./entity/Photo"
  472. import { AppDataSource } from "./index"
  473. const photo = new Photo()
  474. photo.name = "Me and Bears"
  475. photo.description = "I am near polar bears"
  476. photo.filename = "photo-with-bears.jpg"
  477. photo.views = 1
  478. photo.isPublished = true
  479. const photoRepository = AppDataSource.getRepository(Photo)
  480. await photoRepository.save(photo)
  481. console.log("Photo has been saved")
  482. const savedPhotos = await photoRepository.find()
  483. console.log("All photos from the db: ", savedPhotos)
  484. ```
  485. Learn more about Repository [here](./docs/working-with-repository.md).
  486. ### Loading from the database
  487. Let's try more load operations using the Repository:
  488. ```typescript
  489. import { Photo } from "./entity/Photo"
  490. import { AppDataSource } from "./index"
  491. const photoRepository = AppDataSource.getRepository(Photo)
  492. const allPhotos = await photoRepository.find()
  493. console.log("All photos from the db: ", allPhotos)
  494. const firstPhoto = await photoRepository.findOneBy({
  495. id: 1,
  496. })
  497. console.log("First photo from the db: ", firstPhoto)
  498. const meAndBearsPhoto = await photoRepository.findOneBy({
  499. name: "Me and Bears",
  500. })
  501. console.log("Me and Bears photo from the db: ", meAndBearsPhoto)
  502. const allViewedPhotos = await photoRepository.findBy({ views: 1 })
  503. console.log("All viewed photos: ", allViewedPhotos)
  504. const allPublishedPhotos = await photoRepository.findBy({ isPublished: true })
  505. console.log("All published photos: ", allPublishedPhotos)
  506. const [photos, photosCount] = await photoRepository.findAndCount()
  507. console.log("All photos: ", photos)
  508. console.log("Photos count: ", photosCount)
  509. ```
  510. ### Updating in the database
  511. Now let's load a single photo from the database, update it and save it:
  512. ```typescript
  513. import { Photo } from "./entity/Photo"
  514. import { AppDataSource } from "./index"
  515. const photoRepository = AppDataSource.getRepository(Photo)
  516. const photoToUpdate = await photoRepository.findOneBy({
  517. id: 1,
  518. })
  519. photoToUpdate.name = "Me, my friends and polar bears"
  520. await photoRepository.save(photoToUpdate)
  521. ```
  522. Now photo with `id = 1` will be updated in the database.
  523. ### Removing from the database
  524. Now let's remove our photo from the database:
  525. ```typescript
  526. import { Photo } from "./entity/Photo"
  527. import { AppDataSource } from "./index"
  528. const photoRepository = AppDataSource.getRepository(Photo)
  529. const photoToRemove = await photoRepository.findOneBy({
  530. id: 1,
  531. })
  532. await photoRepository.remove(photoToRemove)
  533. ```
  534. Now photo with `id = 1` will be removed from the database.
  535. ### Creating a one-to-one relation
  536. Let's create a one-to-one relationship with another class.
  537. Let's create a new class in `PhotoMetadata.ts`. This PhotoMetadata class is supposed to contain our photo's additional meta-information:
  538. ```typescript
  539. import {
  540. Entity,
  541. Column,
  542. PrimaryGeneratedColumn,
  543. OneToOne,
  544. JoinColumn,
  545. } from "typeorm"
  546. import { Photo } from "./Photo"
  547. @Entity()
  548. export class PhotoMetadata {
  549. @PrimaryGeneratedColumn()
  550. id: number
  551. @Column("int")
  552. height: number
  553. @Column("int")
  554. width: number
  555. @Column()
  556. orientation: string
  557. @Column()
  558. compressed: boolean
  559. @Column()
  560. comment: string
  561. @OneToOne(() => Photo)
  562. @JoinColumn()
  563. photo: Photo
  564. }
  565. ```
  566. Here, we are using a new decorator called `@OneToOne`. It allows us to create a one-to-one relationship between two entities.
  567. `type => Photo` is a function that returns the class of the entity with which we want to make our relationship.
  568. We are forced to use a function that returns a class, instead of using the class directly, because of the language specifics.
  569. We can also write it as `() => Photo`, but we use `type => Photo` as a convention to increase code readability.
  570. The type variable itself does not contain anything.
  571. We also add a `@JoinColumn` decorator, which indicates that this side of the relationship will own the relationship.
  572. Relations can be unidirectional or bidirectional.
  573. Only one side of relational can be owning.
  574. Using `@JoinColumn` decorator is required on the owner side of the relationship.
  575. If you run the app, you'll see a newly generated table, and it will contain a column with a foreign key for the photo relation:
  576. ```shell
  577. +-------------+--------------+----------------------------+
  578. | photo_metadata |
  579. +-------------+--------------+----------------------------+
  580. | id | int(11) | PRIMARY KEY AUTO_INCREMENT |
  581. | height | int(11) | |
  582. | width | int(11) | |
  583. | comment | varchar(255) | |
  584. | compressed | boolean | |
  585. | orientation | varchar(255) | |
  586. | photoId | int(11) | FOREIGN KEY |
  587. +-------------+--------------+----------------------------+
  588. ```
  589. ### Save a one-to-one relation
  590. Now let's save a photo, its metadata and attach them to each other.
  591. ```typescript
  592. import { Photo } from "./entity/Photo"
  593. import { PhotoMetadata } from "./entity/PhotoMetadata"
  594. // create a photo
  595. const photo = new Photo()
  596. photo.name = "Me and Bears"
  597. photo.description = "I am near polar bears"
  598. photo.filename = "photo-with-bears.jpg"
  599. photo.views = 1
  600. photo.isPublished = true
  601. // create a photo metadata
  602. const metadata = new PhotoMetadata()
  603. metadata.height = 640
  604. metadata.width = 480
  605. metadata.compressed = true
  606. metadata.comment = "cybershoot"
  607. metadata.orientation = "portrait"
  608. metadata.photo = photo // this way we connect them
  609. // get entity repositories
  610. const photoRepository = AppDataSource.getRepository(Photo)
  611. const metadataRepository = AppDataSource.getRepository(PhotoMetadata)
  612. // first we should save a photo
  613. await photoRepository.save(photo)
  614. // photo is saved. Now we need to save a photo metadata
  615. await metadataRepository.save(metadata)
  616. // done
  617. console.log(
  618. "Metadata is saved, and the relation between metadata and photo is created in the database too",
  619. )
  620. ```
  621. ### Inverse side of the relationship
  622. Relations can be unidirectional or bidirectional.
  623. Currently, our relation between PhotoMetadata and Photo is unidirectional.
  624. The owner of the relation is PhotoMetadata, and Photo doesn't know anything about PhotoMetadata.
  625. This makes it complicated to access PhotoMetadata from the Photo side.
  626. To fix this issue we should add an inverse relation, and make relations between PhotoMetadata and Photo bidirectional.
  627. Let's modify our entities:
  628. ```typescript
  629. import {
  630. Entity,
  631. Column,
  632. PrimaryGeneratedColumn,
  633. OneToOne,
  634. JoinColumn,
  635. } from "typeorm"
  636. import { Photo } from "./Photo"
  637. @Entity()
  638. export class PhotoMetadata {
  639. /* ... other columns */
  640. @OneToOne(() => Photo, (photo) => photo.metadata)
  641. @JoinColumn()
  642. photo: Photo
  643. }
  644. ```
  645. ```typescript
  646. import { Entity, Column, PrimaryGeneratedColumn, OneToOne } from "typeorm"
  647. import { PhotoMetadata } from "./PhotoMetadata"
  648. @Entity()
  649. export class Photo {
  650. /* ... other columns */
  651. @OneToOne(() => PhotoMetadata, (photoMetadata) => photoMetadata.photo)
  652. metadata: PhotoMetadata
  653. }
  654. ```
  655. `photo => photo.metadata` is a function that returns the name of the inverse side of the relation.
  656. Here we show that the metadata property of the Photo class is where we store PhotoMetadata in the Photo class.
  657. Instead of passing a function that returns a property of the photo, you could alternatively simply pass a string to `@OneToOne` decorator, like `"metadata"`.
  658. But we used this function-typed approach to make our refactoring easier.
  659. Note that we should use the `@JoinColumn` decorator only on one side of a relation.
  660. Whichever side you put this decorator on will be the owning side of the relationship.
  661. The owning side of a relationship contains a column with a foreign key in the database.
  662. ### Relations in ESM projects
  663. If you use ESM in your TypeScript project, you should use the `Relation` wrapper type in relation properties to avoid circular dependency issues.
  664. Let's modify our entities:
  665. ```typescript
  666. import {
  667. Entity,
  668. Column,
  669. PrimaryGeneratedColumn,
  670. OneToOne,
  671. JoinColumn,
  672. Relation,
  673. } from "typeorm"
  674. import { Photo } from "./Photo"
  675. @Entity()
  676. export class PhotoMetadata {
  677. /* ... other columns */
  678. @OneToOne(() => Photo, (photo) => photo.metadata)
  679. @JoinColumn()
  680. photo: Relation<Photo>
  681. }
  682. ```
  683. ```typescript
  684. import {
  685. Entity,
  686. Column,
  687. PrimaryGeneratedColumn,
  688. OneToOne,
  689. Relation,
  690. } from "typeorm"
  691. import { PhotoMetadata } from "./PhotoMetadata"
  692. @Entity()
  693. export class Photo {
  694. /* ... other columns */
  695. @OneToOne(() => PhotoMetadata, (photoMetadata) => photoMetadata.photo)
  696. metadata: Relation<PhotoMetadata>
  697. }
  698. ```
  699. ### Loading objects with their relations
  700. Now let's load our photo and its photo metadata in a single query.
  701. There are two ways to do it - using `find*` methods or using `QueryBuilder` functionality.
  702. Let's use `find*` methods first.
  703. `find*` methods allow you to specify an object with the `FindOneOptions` / `FindManyOptions` interface.
  704. ```typescript
  705. import { Photo } from "./entity/Photo"
  706. import { PhotoMetadata } from "./entity/PhotoMetadata"
  707. import { AppDataSource } from "./index"
  708. const photoRepository = AppDataSource.getRepository(Photo)
  709. const photos = await photoRepository.find({
  710. relations: {
  711. metadata: true,
  712. },
  713. })
  714. ```
  715. Here, photos will contain an array of photos from the database, and each photo will contain its photo metadata.
  716. Learn more about Find Options in [this documentation](./docs/find-options.md).
  717. Using find options is good and dead simple, but if you need a more complex query, you should use `QueryBuilder` instead.
  718. `QueryBuilder` allows more complex queries to be used in an elegant way:
  719. ```typescript
  720. import { Photo } from "./entity/Photo"
  721. import { PhotoMetadata } from "./entity/PhotoMetadata"
  722. import { AppDataSource } from "./index"
  723. const photos = await AppDataSource.getRepository(Photo)
  724. .createQueryBuilder("photo")
  725. .innerJoinAndSelect("photo.metadata", "metadata")
  726. .getMany()
  727. ```
  728. `QueryBuilder` allows the creation and execution of SQL queries of almost any complexity.
  729. When you work with `QueryBuilder`, think like you are creating an SQL query.
  730. In this example, "photo" and "metadata" are aliases applied to selected photos.
  731. You use aliases to access columns and properties of the selected data.
  732. ### Using cascades to automatically save related objects
  733. We can set up cascade options in our relations, in the cases when we want our related object to be saved whenever the other object is saved.
  734. Let's change our photo's `@OneToOne` decorator a bit:
  735. ```typescript
  736. export class Photo {
  737. // ... other columns
  738. @OneToOne(() => PhotoMetadata, (metadata) => metadata.photo, {
  739. cascade: true,
  740. })
  741. metadata: PhotoMetadata
  742. }
  743. ```
  744. Using `cascade` allows us not to separately save photo and separately save metadata objects now.
  745. Now we can simply save a photo object, and the metadata object will be saved automatically because of cascade options.
  746. ```typescript
  747. import { AppDataSource } from "./index"
  748. // create photo object
  749. const photo = new Photo()
  750. photo.name = "Me and Bears"
  751. photo.description = "I am near polar bears"
  752. photo.filename = "photo-with-bears.jpg"
  753. photo.isPublished = true
  754. // create photo metadata object
  755. const metadata = new PhotoMetadata()
  756. metadata.height = 640
  757. metadata.width = 480
  758. metadata.compressed = true
  759. metadata.comment = "cybershoot"
  760. metadata.orientation = "portrait"
  761. photo.metadata = metadata // this way we connect them
  762. // get repository
  763. const photoRepository = AppDataSource.getRepository(Photo)
  764. // saving a photo also save the metadata
  765. await photoRepository.save(photo)
  766. console.log("Photo is saved, photo metadata is saved too.")
  767. ```
  768. Notice that we now set the photo's `metadata` property, instead of the metadata's `photo` property as before. The `cascade` feature only works if you connect the photo to its metadata from the photo's side. If you set the metadata's side, the metadata would not be saved automatically.
  769. ### Creating a many-to-one / one-to-many relation
  770. Let's create a many-to-one/one-to-many relation.
  771. Let's say a photo has one author, and each author can have many photos.
  772. First, let's create an `Author` class:
  773. ```typescript
  774. import {
  775. Entity,
  776. Column,
  777. PrimaryGeneratedColumn,
  778. OneToMany,
  779. JoinColumn,
  780. } from "typeorm"
  781. import { Photo } from "./Photo"
  782. @Entity()
  783. export class Author {
  784. @PrimaryGeneratedColumn()
  785. id: number
  786. @Column()
  787. name: string
  788. @OneToMany(() => Photo, (photo) => photo.author) // note: we will create author property in the Photo class below
  789. photos: Photo[]
  790. }
  791. ```
  792. `Author` contains an inverse side of a relation.
  793. `OneToMany` is always an inverse side of the relation, and it can't exist without `ManyToOne` on the other side of the relation.
  794. Now let's add the owner side of the relation into the Photo entity:
  795. ```typescript
  796. import { Entity, Column, PrimaryGeneratedColumn, ManyToOne } from "typeorm"
  797. import { PhotoMetadata } from "./PhotoMetadata"
  798. import { Author } from "./Author"
  799. @Entity()
  800. export class Photo {
  801. /* ... other columns */
  802. @ManyToOne(() => Author, (author) => author.photos)
  803. author: Author
  804. }
  805. ```
  806. In many-to-one / one-to-many relation, the owner side is always many-to-one.
  807. It means that the class that uses `@ManyToOne` will store the id of the related object.
  808. After you run the application, the ORM will create the `author` table:
  809. ```shell
  810. +-------------+--------------+----------------------------+
  811. | author |
  812. +-------------+--------------+----------------------------+
  813. | id | int(11) | PRIMARY KEY AUTO_INCREMENT |
  814. | name | varchar(255) | |
  815. +-------------+--------------+----------------------------+
  816. ```
  817. It will also modify the `photo` table, adding a new `author` column and creating a foreign key for it:
  818. ```shell
  819. +-------------+--------------+----------------------------+
  820. | photo |
  821. +-------------+--------------+----------------------------+
  822. | id | int(11) | PRIMARY KEY AUTO_INCREMENT |
  823. | name | varchar(255) | |
  824. | description | varchar(255) | |
  825. | filename | varchar(255) | |
  826. | isPublished | boolean | |
  827. | authorId | int(11) | FOREIGN KEY |
  828. +-------------+--------------+----------------------------+
  829. ```
  830. ### Creating a many-to-many relation
  831. Let's create a many-to-many relation.
  832. Let's say a photo can be in many albums, and each album can contain many photos.
  833. Let's create an `Album` class:
  834. ```typescript
  835. import {
  836. Entity,
  837. PrimaryGeneratedColumn,
  838. Column,
  839. ManyToMany,
  840. JoinTable,
  841. } from "typeorm"
  842. @Entity()
  843. export class Album {
  844. @PrimaryGeneratedColumn()
  845. id: number
  846. @Column()
  847. name: string
  848. @ManyToMany(() => Photo, (photo) => photo.albums)
  849. @JoinTable()
  850. photos: Photo[]
  851. }
  852. ```
  853. `@JoinTable` is required to specify that this is the owner side of the relationship.
  854. Now let's add the inverse side of our relation to the `Photo` class:
  855. ```typescript
  856. export class Photo {
  857. // ... other columns
  858. @ManyToMany(() => Album, (album) => album.photos)
  859. albums: Album[]
  860. }
  861. ```
  862. After you run the application, the ORM will create a **album_photos_photo_albums** _junction table_:
  863. ```shell
  864. +-------------+--------------+----------------------------+
  865. | album_photos_photo_albums |
  866. +-------------+--------------+----------------------------+
  867. | album_id | int(11) | PRIMARY KEY FOREIGN KEY |
  868. | photo_id | int(11) | PRIMARY KEY FOREIGN KEY |
  869. +-------------+--------------+----------------------------+
  870. ```
  871. Don't forget to register the `Album` class with your connection in the ORM:
  872. ```typescript
  873. const options: DataSourceOptions = {
  874. // ... other options
  875. entities: [Photo, PhotoMetadata, Author, Album],
  876. }
  877. ```
  878. Now let's insert albums and photos to our database:
  879. ```typescript
  880. import { AppDataSource } from "./index"
  881. // create a few albums
  882. const album1 = new Album()
  883. album1.name = "Bears"
  884. await AppDataSource.manager.save(album1)
  885. const album2 = new Album()
  886. album2.name = "Me"
  887. await AppDataSource.manager.save(album2)
  888. // create a few photos
  889. const photo = new Photo()
  890. photo.name = "Me and Bears"
  891. photo.description = "I am near polar bears"
  892. photo.filename = "photo-with-bears.jpg"
  893. photo.views = 1
  894. photo.isPublished = true
  895. photo.albums = [album1, album2]
  896. await AppDataSource.manager.save(photo)
  897. // now our photo is saved and albums are attached to it
  898. // now lets load them:
  899. const loadedPhoto = await AppDataSource.getRepository(Photo).findOne({
  900. where: {
  901. id: 1,
  902. },
  903. relations: {
  904. albums: true,
  905. },
  906. })
  907. ```
  908. `loadedPhoto` will be equal to:
  909. ```typescript
  910. {
  911. id: 1,
  912. name: "Me and Bears",
  913. description: "I am near polar bears",
  914. filename: "photo-with-bears.jpg",
  915. albums: [{
  916. id: 1,
  917. name: "Bears"
  918. }, {
  919. id: 2,
  920. name: "Me"
  921. }]
  922. }
  923. ```
  924. ### Using QueryBuilder
  925. You can use QueryBuilder to build SQL queries of almost any complexity. For example, you can do this:
  926. ```typescript
  927. const photos = await AppDataSource.getRepository(Photo)
  928. .createQueryBuilder("photo") // first argument is an alias. Alias is what you are selecting - photos. You must specify it.
  929. .innerJoinAndSelect("photo.metadata", "metadata")
  930. .leftJoinAndSelect("photo.albums", "album")
  931. .where("photo.isPublished = true")
  932. .andWhere("(photo.name = :photoName OR photo.name = :bearName)")
  933. .orderBy("photo.id", "DESC")
  934. .skip(5)
  935. .take(10)
  936. .setParameters({ photoName: "My", bearName: "Mishka" })
  937. .getMany()
  938. ```
  939. This query selects all published photos with "My" or "Mishka" names.
  940. It will select results from position 5 (pagination offset)
  941. and will select only 10 results (pagination limit).
  942. The selection result will be ordered by id in descending order.
  943. The photo's albums will be left joined and their metadata will be inner joined.
  944. You'll use the query builder in your application a lot.
  945. Learn more about QueryBuilder [here](./docs/select-query-builder.md).
  946. ## Samples
  947. Take a look at the samples in [sample](https://github.com/typeorm/typeorm/tree/master/sample) for examples of usage.
  948. There are a few repositories which you can clone and start with:
  949. - [Example how to use TypeORM with TypeScript](https://github.com/typeorm/typescript-example)
  950. - [Example how to use TypeORM with JavaScript](https://github.com/typeorm/javascript-example)
  951. - [Example how to use TypeORM with JavaScript and Babel](https://github.com/typeorm/babel-example)
  952. - [Example how to use TypeORM with TypeScript and SystemJS in Browser](https://github.com/typeorm/browser-example)
  953. - [Example how to use TypeORM with TypeScript and React in Browser](https://github.com/ItayGarin/typeorm-react-swc)
  954. - [Example how to use Express and TypeORM](https://github.com/typeorm/typescript-express-example)
  955. - [Example how to use Koa and TypeORM](https://github.com/typeorm/typescript-koa-example)
  956. - [Example how to use TypeORM with MongoDB](https://github.com/typeorm/mongo-typescript-example)
  957. - [Example how to use TypeORM in a Cordova/PhoneGap app](https://github.com/typeorm/cordova-example)
  958. - [Example how to use TypeORM with an Ionic app](https://github.com/typeorm/ionic-example)
  959. - [Example how to use TypeORM with React Native](https://github.com/typeorm/react-native-example)
  960. - [Example how to use TypeORM with Nativescript-Vue](https://github.com/typeorm/nativescript-vue-typeorm-sample)
  961. - [Example how to use TypeORM with Nativescript-Angular](https://github.com/betov18x/nativescript-angular-typeorm-example)
  962. - [Example how to use TypeORM with Electron using JavaScript](https://github.com/typeorm/electron-javascript-example)
  963. - [Example how to use TypeORM with Electron using TypeScript](https://github.com/typeorm/electron-typescript-example)
  964. ## Extensions
  965. There are several extensions that simplify working with TypeORM and integrating it with other modules:
  966. - [TypeORM + GraphQL framework](https://github.com/vesper-framework/vesper)
  967. - [TypeORM integration](https://github.com/typeorm/typeorm-typedi-extensions) with [TypeDI](https://github.com/pleerock/typedi)
  968. - [TypeORM integration](https://github.com/typeorm/typeorm-routing-controllers-extensions) with [routing-controllers](https://github.com/pleerock/routing-controllers)
  969. - Models generation from existing database - [typeorm-model-generator](https://github.com/Kononnable/typeorm-model-generator)
  970. - Fixtures loader - [typeorm-fixtures-cli](https://github.com/RobinCK/typeorm-fixtures)
  971. - ER Diagram generator - [typeorm-uml](https://github.com/eugene-manuilov/typeorm-uml/)
  972. - another ER Diagram generator - [erdia](https://www.npmjs.com/package/erdia/)
  973. - Create, drop & seed database - [typeorm-extension](https://github.com/tada5hi/typeorm-extension)
  974. - Automatically update `data-source.ts` after generating migrations/entities - [typeorm-codebase-sync](https://www.npmjs.com/package/typeorm-codebase-sync)
  975. - Easy manipulation of `relations` objects - [typeorm-relations](https://npmjs.com/package/typeorm-relations)
  976. - Automatically generate `relations` based on a GraphQL query - [typeorm-relations-graphql](https://npmjs.com/package/typeorm-relations-graphql)
  977. ## Contributing
  978. Learn about contribution [here](https://github.com/typeorm/typeorm/blob/master/CONTRIBUTING.md) and how to setup your development environment [here](https://github.com/typeorm/typeorm/blob/master/DEVELOPER.md).
  979. This project exists thanks to all the people who contribute:
  980. <a href="https://github.com/typeorm/typeorm/graphs/contributors"><img src="https://opencollective.com/typeorm/contributors.svg?width=890&showBtn=false" /></a>
  981. ## Sponsors
  982. Open source is hard and time-consuming. If you want to invest in TypeORM's future you can become a sponsor and allow our core team to spend more time on TypeORM's improvements and new features. [Become a sponsor](https://opencollective.com/typeorm)
  983. <a href="https://opencollective.com/typeorm" target="_blank"><img src="https://opencollective.com/typeorm/tiers/sponsor.svg?width=890"></a>
  984. ## Gold Sponsors
  985. Become a gold sponsor and get premium technical support from our core contributors. [Become a gold sponsor](https://opencollective.com/typeorm)
  986. <a href="https://opencollective.com/typeorm" target="_blank"><img src="https://opencollective.com/typeorm/tiers/gold-sponsor.svg?width=890"></a>
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/661356
推荐阅读
相关标签
  

闽ICP备14008679号

        
cppcmd=keepalive&