• 使用 JavaScript
    • app.js
    • entity/Category.js
    • entity/Post.js

    使用 JavaScript

    TypeORM 不仅可以用于 TypeScript,还可以用于 JavaScript。 一切都是一样的,除了需要省略类型,如果你的平台不支持 ES6 类,那么你需要定义具有所有必需元数据的对象。

    app.js

    1. var typeorm = require("typeorm");
    2. typeorm
    3. .createConnection({
    4. type: "postgres",
    5. host: "localhost",
    6. port: 5432,
    7. username: "test",
    8. password: "admin",
    9. database: "test",
    10. synchronize: true,
    11. entitySchemas: [require("./entity/Post"), require("./entity/Category")]
    12. })
    13. .then(function(connection) {
    14. var category1 = {
    15. name: "TypeScript"
    16. };
    17. var category2 = {
    18. name: "Programming"
    19. };
    20. var post = {
    21. title: "Control flow based type analysis",
    22. text: "TypeScript 2.0 implements a control flow-based type analysis for local variables and parameters.",
    23. categories: [category1, category2]
    24. };
    25. var postRepository = connection.getRepository("Post");
    26. postRepository
    27. .save(post)
    28. .then(function(savedPost) {
    29. console.log("Post has been saved: ", savedPost);
    30. console.log("Now lets load all posts: ");
    31. return postRepository.find();
    32. })
    33. .then(function(allPosts) {
    34. console.log("All posts: ", allPosts);
    35. });
    36. })
    37. .catch(function(error) {
    38. console.log("Error: ", error);
    39. });

    entity/Category.js

    1. module.exports = {
    2. name: "Category",
    3. columns: {
    4. id: {
    5. primary: true,
    6. type: "int",
    7. generated: true
    8. },
    9. name: {
    10. type: "string"
    11. }
    12. }
    13. };

    entity/Post.js

    1. module.exports = {
    2. name: "Post",
    3. columns: {
    4. id: {
    5. primary: true,
    6. type: "int",
    7. generated: true
    8. },
    9. title: {
    10. type: "string"
    11. },
    12. text: {
    13. type: "text"
    14. }
    15. },
    16. relations: {
    17. categories: {
    18. target: "Category",
    19. type: "many-to-many",
    20. joinTable: true,
    21. cascade: true
    22. }
    23. }
    24. };

    您可以查看此示例typeorm/javascript-example以了解更多信息。