Tags
import {
Entity,
PrimaryGeneratedColumn,
Column,
ManyToMany,
JoinTable
} from "typeorm"
import { Posts } from "./Posts"
@Entity({ name: "tags" })
export class Tags {
@PrimaryGeneratedColumn({
type: "int",
name: "id",
comment: "主键id"
})
id: number
@Column({
type: "varchar",
name: "name",
nullable: false,
unique: true,
comment: "标签名称"
})
name: string
@ManyToMany(type => Posts, posts => posts.tags)
@JoinTable({ name: "tags_posts" })
posts: Posts[]
}
Posts
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn,
ManyToOne,
ManyToMany
} from "typeorm"
import { Tags } from "./Tags"
import { User } from "./User"
@Entity({ name: "posts" })
export class Posts {
@PrimaryGeneratedColumn({
type: "int",
name: "id",
comment: "主键id"
})
id: number
@Column({
type: "varchar",
nullable: false,
length: 50,
unique: true,
name: "title",
comment: "标题"
})
title: string
@Column({
type: "text",
nullable: false,
name: "content",
comment: "内容"
})
content: string
@Column("tinyint", {
nullable: false,
default: () => 0,
name: "is_del",
comment: "是否删除, 1表示删除, 0表示正常"
})
isDel: number
@CreateDateColumn({
type: "timestamp",
nullable: false,
name: "created_at",
comment: "创建时间"
})
createdAt: Date
@UpdateDateColumn({
type: "timestamp",
nullable: false,
name: "update_at",
comment: "更新时间"
})
updateAt: Date
@ManyToOne(type => User, user => user.posts)
user: User
@ManyToMany(type => Tags, tag => tag.posts)
tags: Tags[]
}
数据操作
import "reflect-metadata";
import { createConnection } from "typeorm";
import { User } from "./entity/User";
import { UserExtend } from "./entity/UserExtend"
import { Posts } from "./entity/Posts"
import { Tags } from "./entity/Tags"
createConnection()
.then(async (connection) => {
const tag1 = new Tags()
tag1.name = "mysql"
const tag2 = new Tags()
tag2.name = "node"
const posts1 = new Posts()
posts1.title = "文章一"
posts1.content = "文章一内容"
posts1.tags = [tag1, tag2]
const posts2 = new Posts()
posts2.title = "文章二"
posts2.content = "文章二内容"
posts2.tags = [tag1, tag2]
const user = new User()
user.username = "张龙"
user.password = "654321"
user.posts = [posts1, posts2]
const userRepository = connection.getRepository(User)
const postsRepository = connection.getRepository(Posts)
const tagRepository = connection.getRepository(Tags)
await tagRepository.save(tag1)
await tagRepository.save(tag2)
await postsRepository.save(posts1)
await postsRepository.save(posts2)
await userRepository.save(user)
console.log("添加数据成功")
const result = await postsRepository.find({ relations: ["tags", "user"]})
console.log(result);
})
.catch((error) => console.log(error));