跳至主内容区

在 JavaScript 中使用

非官方测试版翻译

本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →

TypeORM 不仅支持 TypeScript,同样也适用于 JavaScript。 除需省略类型声明外,其余用法完全一致。若您的运行环境不支持 ES6 类语法,则需通过对象字面量定义完整的元数据。

app.js
var typeorm = require("typeorm")

var dataSource = new typeorm.DataSource({
type: "postgres",
host: "localhost",
port: 5432,
username: "test",
password: "admin",
database: "test",
synchronize: true,
entities: [require("./entities/Post"), require("./entities/Category")],
})

dataSource
.initialize()
.then(function () {
var category1 = {
name: "TypeScript",
}
var category2 = {
name: "Programming",
}

var post = {
title: "Control flow based type analysis",
text: "TypeScript 2.0 implements a control flow-based type analysis for local variables and parameters.",
categories: [category1, category2],
}

var postRepository = dataSource.getRepository("Post")
postRepository
.save(post)
.then(function (savedPost) {
console.log("Post has been saved: ", savedPost)
console.log("Now lets load all posts: ")

return postRepository.find()
})
.then(function (allPosts) {
console.log("All posts: ", allPosts)
})
})
.catch(function (error) {
console.log("Error: ", error)
})
entity/Category.js
var EntitySchema = require("typeorm").EntitySchema

module.exports = new EntitySchema({
name: "Category", // Will use table name `category` as default behaviour.
tableName: "categories", // Optional: Provide `tableName` property to override the default behaviour for table name.
columns: {
id: {
primary: true,
type: "int",
generated: true,
},
name: {
type: "varchar",
},
},
})
entity/Post.js
var EntitySchema = require("typeorm").EntitySchema

module.exports = new EntitySchema({
name: "Post", // Will use table name `post` as default behaviour.
tableName: "posts", // Optional: Provide `tableName` property to override the default behaviour for table name.
columns: {
id: {
primary: true,
type: "int",
generated: true,
},
title: {
type: "varchar",
},
text: {
type: "text",
},
},
relations: {
categories: {
target: "Category",
type: "many-to-many",
joinTable: true,
cascade: true,
},
},
})

请参考示例项目 typeorm/javascript-example 获取完整实现。