usage-with-javascript
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("./entity/Post"), require("./entity/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", // 默认情况下将使用表名 `category`。
tableName: "categories", // 可选: 提供 `tableName` 属性来覆盖表名的默认行为。
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", // 默认情况下将使用表名 `post`。
tableName: "posts", // 可选: 提供 `tableName` 属性来覆盖表名的默认行为。
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 以了解更多信息。