Many to Many Entities in Typeorm
HTML-код
- Опубликовано: 9 окт 2024
- Learn how to create many to many relationships with Typeorm.
Code: github.com/ben...
Links from video: typeorm.io/#/on...
----
Video Suggestions:
Trello: trello.com/b/m...
Join the Trello board: trello.com/inv...
----
Follow Me Online Here:
GitHub: github.com/ben...
LinkedIn: / benawad
Instagram: / benawad97
Patreon: / benawad
----
Join the Discord: / discord
Twitter: / benawad
#benawad
TikTok: / benawad
----
Follow me online: voidpet.com/be...
#benawad
Just an FYI for anyone else trying this out: The decorators on the join columns seem to need to be ManyToOne now. If you use OneToOne and you have the "synchronize" flag set to true, your app will be unable to synchronize as TypeORM will try to create a uniqueness constraint on your keys on app start, which will fail since your table is many-to-many and you may have, for example, a single user editing multiple posts. Otherwise this technique works perfectly!
you answered my question a year before I even had the question, thanks dude
typeorm should add this to their doc. This is a common use case, like activerecord has_many :through association. good job Ben!
yes! This what I am about to say.
PS: Whenever I switch to a new framework, I really miss Rails' Active Record.
Awesome! Just what I needed. They definitely should add this to the official docs
I use this a lot on securing information. That allows us to obscure parts of the sensitive information, like info from the cardholder data. We split data like, the cardnumber and expiration, into one server protected by an independent nacl and securitygroup, other part like the holder's name and billing into other server, all data heavily encrypted at rest with only knonw by the user keys. Keep different parts of the information neeeded to perform a payment with that data.
In your custom many-to-many example would it not be many-to-one to each of the other tables?
Also what they have in the updated docs:
@ManyToOne(type => Post, post => post.postToCategories)
public post!: Post;
@ManyToOne(type => Category, category => category.postToCategories)
public category!: Category;
> In your custom many-to-many example would it not be many-to-one to each of the other tables?
yep exactly
@@bawad k. just because in the video I think you did one-to-one but thanks
If I have an auto-generated many to many table which has data and I want to add an additional column to it, is it advisable to take over management of the table manually to add the column or is it better to create an additional manually managed many-to-many table where any custom columns can be added?
How to query this thing correctly with the repository functionality, for example findOne({...})?
Can you show, how to do a polymorphic relationship with typeorm?
Thanks for your videos! You explained a lot of things to me. But I have one problem with TypeORM. In my projects, I always have linting enabled. To avoid the dependency cycle I turn on the Eslint proper rule to detect ones. But with TypeORM Entities, there is a problem, because you have to import them from each other... Do you know any solution without turning off that rule and without losing advantages od class base Entities? (I wouldn't like to use Entity Schemas).
@Ben
Thanks for the video!
So if you create a separate join table, you don’t need The ManyToMany decorator in Post.ts?
Correct
It'd been helpful if you showed us how to query the resultset using your entities....
Typeorm looks cool - sad to see you stopping? Do you think it needs more time before it is a viable tool for you?
I'm going to continue using it and will use it with my boilerplate, I'm done making videos directly about Typeorm features (I'll probably come back to it).
Hello Ben, how do I implement polymorphic relationship in typeorm
Hi Ben,
Did you succeed in running a type orm with postgres with node?
I upgraded typeorm and i got an error: No metadata for "User" was found.
The latest versions:
"devDependencies": {
"ts-node": "3.3.0",
"@types/node": "^8.0.29",
"typescript": "2.5.2"
},
"dependencies": {
"typeorm": "0.1.16",
"reflect-metadata": "^0.1.10",
"pg": "^7.3.0"
},
i run tsc -p tsconfig.json to deploy/build
I started a testproject with the typeorm cli.
for development this works fine:
nodemon --exec ts-node src/index.ts
the tsconfig.json is:
{
"compilerOptions": {
"lib": [
"es5",
"es6"
],
"target": "es6",
"module": "commonjs",
"moduleResolution": "node",
"outDir": "./build",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true
}
}
my guess is that typeorm is not ready yet for production, but i read that it was used for production.
Any idea?
thanks!
I believe it does work in production, I'll give it a try with the latest version and let you know
Ok I got the same error the first time I did it too. In ormconfig you just need to change .ts to .js because all the files have been converted to js
i tried that and worked when i run start.
when i build and run the server it gives the error: { EntityMetadataNotFound: No metadata for "User" was found.
You keep the original tsconfig.json?
this supposed to be solved by the import: import * as metadata from "reflect-metadata";
"scripts": {
"start": "nodemon --exec ts-node src/index.ts",
"build": "rimraf build && tsc -p tsconfig.json",
"start-server": "node build/index.js"
}
tried some different approaches too.
This one was promising:
import { Connection, createConnection } from "typeorm";
import { User } from "../entity/User";
export interface IDatabaseConfiguration {
type: "postgres" | "mysql" | "mssql";
host: string;
port: number;
username: string;
password: string;
database: string;
ssl?: boolean;
}
export class DatabaseProvider {
private static connection: Connection;
private static configuration: IDatabaseConfiguration;
public static configure(databaseConfiguration: IDatabaseConfiguration): void {
DatabaseProvider.configuration = databaseConfiguration;
}
public static async getConnection(): Promise {
if (DatabaseProvider.connection) {
return DatabaseProvider.connection;
}
DatabaseProvider.configure({
type: process.env.DATABASE_TYPE as any || "postgres",
database: process.env.DATABASE_NAME || "testdatabase",
username: process.env.DATABASE_USERNAME || "xxx",
password: process.env.DATABASE_PASSWORD || "xxx",
host: process.env.DATABASE_HOST || "localhost",
port: +process.env.DATABASE_PORT || 5432,
ssl: !!process.env.USE_SSL
});
if (!DatabaseProvider.configuration) {
throw new Error("DatabaseProvider is not configured yet.");
}
const { type, host, port, username, password, database, ssl } = DatabaseProvider.configuration;
DatabaseProvider.connection = await createConnection({
type, host, port, username, password, database,
extra: {
ssl
},
entities: [
User
],
autoSchemaSync: true
} as any); // as any to prevent complaining about the object does not fit to MongoConfiguration, which we won't use here
return DatabaseProvider.connection;
}
}
Thanks!
it worked for me when building.
If your getting that error, Typeorm is having trouble finding your entities. Something is wrong with your ormconfig.json
The code snippet you posted looks like it should work
Ben Awad . I got it working. I figured out how to use it in development mode and production. I use the js format for orm and set the extensions to .ts in dev mode and .js in prod mode. Now I can use just 1 config file for dev and prod. 😃
Thanks for responding!
Is there an easy way to use many to manage many to many state in the frontend of React? I'm using Django btw not Typeorm.
mobx?
Hi Ben, how would you bundle and deploy this typescript server?
All I would do is run `tsc` to convert it javascript and then it's good to go. I would use Node to run it: `node dist/index.js`
Hi Ben, i did exactly that! But i got: SyntaxError: Unexpected token import
So the imports are not converted correctly i think...
Just tried it and got the same thing.
It's because ormconfig.json tells typeorm that the entities are in src/entity/**/*.ts
You would want to create a different ormconfig for deploying where you replace `src` with `dist` or whatever you called your folder.
ok.. glad you had thesame... :-) thanks Ben!
I will make another config file
Hella confusing