0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Prisma と Typeorm の比較

Posted at

Prisma と Typeorm の比較

参考文献

Typeormの資料: https://orkhan.gitbook.io/typeorm
Prismaの資料: https://www.prisma.io/

relation の書き方

以下のようなデータの構造で article にあとから authoruser 外部キーとして追加するコードの違いを見てみます。

erDiagram
    user ||--o{ article : ""

    user {
        bigint id PK "ID"
        string name "名前"
        string email "メールアドレス"
    }

    article {
        bigint id PK "ID"
        string title "タイトル"
        string content "内容"
        references author FK
    }

prisma

model User {
  id       Int       @id @default(autoincrement())
  name     String
  email    String    @unique
}

model Article {
  id       Int    @id @default(autoincrement())
  title    String
  content  String?
  authorId Int
  author   User   @relation(fields: [authorId], references: [id])
}
const prisma = new PrismaClient();
const updatedArticle = await prisma.article.update({
    where: { id: articleId },
    data: {
      author: {
        connect: { id: userId },
      },
    },
  });

typeorm

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @Column({ unique: true })
  email: string;
}

@Entity()
export class Article {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  title: string;

  @Column({ nullable: true })
  content: string;

  @ManyToOne(() => User, user => user.articles)
  author: User;
}
const connection = await createConnection();
const userRepository = connection.getRepository(User);
const articleRepository = connection.getRepository(Article);

const user = await userRepository.findOne(userId);
const article = await articleRepository.findOne(articleId);

article.author = user;
await articleRepository.save(article);

relation を書く上での可読性や構文は prisma の方が優れているようです。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?