10

我有两个实体:UserHabit。用户可以创建多个习惯,因此我在用户上使用OneToMany关系(分别在习惯上使用ManyToOne)。

用户实体

import {Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn, BeforeInsert, BeforeUpdate, OneToMany} from "typeorm";
import * as bcrypt from "bcryptjs";
import { Habit } from "../habits/habits.entity";

@Entity()
export class User {
    @PrimaryGeneratedColumn("uuid")
    id: string;

    @Column()
    name: string;

    @Column()
    email: string;

    @Column()
    password: string;

    @OneToMany(type => Habit, habit => habit.author)
    habits: Habit[];

    @CreateDateColumn()
    dateCreated: Date;

    @UpdateDateColumn()
    dateUpdated: Date;

    @BeforeInsert()
    @BeforeUpdate()
    async hashPassword(): Promise<void> {
        this.password = await bcrypt.hash(this.password,10);
    }

    async comparePassword(password: string): Promise<boolean> {
        return bcrypt.compare(password, this.password);
    }

    constructor(props: any) {
        Object.assign(this, props);
    }
}

习惯实体

import {Column, CreateDateColumn, Entity, PrimaryGeneratedColumn, UpdateDateColumn, ManyToOne} from "typeorm";
import { User } from "../users/users.entity";

@Entity()
export class Habit {
    @PrimaryGeneratedColumn("uuid")
    id: string;

    @Column()
    name: string;

    @Column({ nullable: true})
    description?: string;

    @ManyToOne(type => User, user => user.habits)
    author: User;

    @CreateDateColumn()
    dateCreated: Date;

    @UpdateDateColumn()
    dateUpdated: Date;

    constructor(props: Partial<Habit>) {
        Object.assign(this, props);
    }
}

问题

设置上述关系时,我收到以下错误

WARNING in Circular dependency detected:
apps\api\src\habits\habits.entity.ts -> apps\api\src\users\users.entity.ts -> apps\api\src\habits\habits.entity.ts

WARNING in Circular dependency detected:
apps\api\src\users\users.entity.ts -> apps\api\src\habits\habits.entity.ts -> apps\api\src\users\users.entity.ts


/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "User", function() { return User; });
                                                                                               ^
ReferenceError: Cannot access 'User' before initialization
    at Module.User (...\dist\apps\api\main.js:1782:96)
    at Module../apps/api/src/habits/habits.entity.ts (...\dist\apps\api\webpack:\apps\api\src\habits\habits.entity.ts:42:13)
    at __webpack_require__ (...\dist\apps\api\webpack:\webpack\bootstrap:19:1)
    at Module../apps/api/src/users/users.entity.ts (...\dist\apps\api\main.js:1790:79)
    at __webpack_require__ (...\dist\apps\api\webpack:\webpack\bootstrap:19:1)
    at Module../apps/api/src/config/db-config.service.ts (...\dist\apps\api\main.js:1038:77)
    at __webpack_require__ (...\dist\apps\api\webpack:\webpack\bootstrap:19:1)
    at Module../apps/api/src/config/config.module.ts (...\dist\apps\api\main.js:978:76)
    at __webpack_require__ (...\dist\apps\api\webpack:\webpack\bootstrap:19:1)
    at Module../apps/api/src/app/app.module.ts (...\dist\apps\api\main.js:147:79)

笔记

我使用Nx并创建了一个NestJS应用程序。TypeOrm 版本是“^0.2.22”,@nestjs/typeorm 版本是“^6.2.0”

我的tsconfig如下:

{
  "compileOnSave": false,
  "compilerOptions": {
    "rootDir": ".",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "target": "es2015",
    "module": "esnext",
    "typeRoots": ["node_modules/@types"],
    "lib": ["es2018", "dom"],
    "skipLibCheck": true,
    "skipDefaultLibCheck": true,
    "baseUrl": ".",
    "paths": {
      "@awhile/contracts": ["libs/contracts/src/index.ts"],
      "@awhile/ui": ["libs/ui/src/index.ts"]
    }
  },
  "exclude": ["node_modules", "tmp"]
}

我尝试使用ManyToMany关系并且它有效。此外,在单独的 NestJS 应用程序(没有 Nx)上,我无法重现此参考错误。在tsconfig.json中更改 ECMAScript目标版本也不起作用。

这两个实体仅在其服务中使用,并未在其他任何地方实例化。

我很感激任何帮助。先感谢您。

4

3 回答 3

7

在 tsconfig 中,将目标设置为“esnext”并将模块设置为“commonjs”为我解决了这个问题

{
  "extends": "../../tsconfig.json",
  "compilerOptions": {
    "types": ["node", "jest"],
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "module": "commonjs",
    "target": "esnext"
  },
  "include": ["**/*.ts"]
}
于 2020-04-15T19:54:07.427 回答
3

我在将 TypeORM 配置加载到 NestJS 时使用 autoLoadEntities: true 解决了这个问题。请注意,这是 NestJS 的额外内容,因此如果您使用 ormconfig.json,则不会应用此属性。

这里的 autoLoadEntities 文档:https ://docs.nestjs.com/techniques/database#auto-load-entities

2020 年 4 月 10 日更新

我一直对关系有同样的问题。我发现的另一个解决方案,即使它违反了一些标准,也是将所有实体添加到一个文件中。在那里导出它们并在需要的地方导入它们。

请记住,声明类的顺序很重要。

于 2020-04-01T18:28:34.087 回答
2

您可以使用桶文件完成与@jdruper 相同的事情。如果您的 tsconfig.json 中没有 paths 属性,请在下面添加一个compilerOptions如下所示的属性:

"paths": {
   "@entities":["app/src/entities/index.ts"]
}

将所有实体类放在实体文件夹中,创建 index.ts 文件并在 index.ts 文件中添加导出语句:

export * from './user.entity';
export * from './habit.entity';

确保导出语句按要求的顺序出现。然后,您的导入将如下所示。

import { User, Habit } from '@entities';

您可以搜索打字稿桶文件以获取有关如何使用桶文件的更多信息。

如果您使用的是 NX,您可以创建一个实体库并完成同样的事情。

这可能意味着必须将所有实体文件一起移动并更新模块和服务中的导入。也许并不完全理想,但我更喜欢将它们全部放在一个文件中。

于 2020-05-20T15:26:59.593 回答