【问题标题】:How I can use exist table in mysql using typeorm entity?如何使用 typeorm 实体在 mysql 中使用现有表?
【发布时间】:2020-03-21 18:15:42
【问题描述】:

使用 typeorm,我连接到 mysql 数据库。数据库中已经存在几个表。我尝试使用实体模块来描述表,但我的定义覆盖了现有表。如何使用实体从现有表中完全继承?

import "reflect-metadata";
import { Entity, PrimaryGeneratedColumn, Column, PrimaryColumn, OneToMany } from "typeorm";

@Entity("devices")
export class Devices {
    @PrimaryGeneratedColumn()
    ID: number;

    @Column({ type: "varchar", length: 255 })
    Name: string;

    @Column({ type: "int", nullable: false })
    DevID: number;

    @Column({ type: "int", nullable: false })
    Longtitude: number;

    @Column({ type: "int", nullable: false })
    Latitude: number;

    @PrimaryColumn({ type: "varchar", length: 255 })
    URL_VWS: string;
}

【问题讨论】:

  • 你的表是如何在 Mysql 中定义的,你应该提供它的模式,因为没有它就不可能回答你的问题
  • 您还应该提供带有迁移和同步信息的ormconfig.json 文件。如果您使用sync 选项,您将无法安全地处理它。

标签: javascript mysql node.js express typeorm


【解决方案1】:

您可以使用@Entity 将同步属性设置为 false,如下所示。

@Entity({name:"devices", synchronize: false})

【讨论】:

【解决方案2】:

在 ormconfig.json 中

改变

{
  "type": "mysql",
  "host": "localhost",
  "port": 3306,
  "database": "demo",
  "username": "root",
  "entities": ["src/**/**.entity{.ts,.js}"],
  "synchronize": true
}

{
  "type": "mysql",
  "host": "localhost",
  "port": 3306,
  "database": "demo",
  "username": "root",
  "entities": ["src/**/**.entity{.ts,.js}"],
  "synchronize": false
}

【讨论】:

    猜你喜欢
    • 2020-09-07
    • 2019-04-03
    • 2019-05-24
    • 1970-01-01
    • 2022-01-06
    • 2019-06-04
    • 2021-10-27
    • 1970-01-01
    • 2020-08-29
    相关资源
    最近更新 更多