node.js - 如何从 NestJS/TypeORM 中父级的连接字段访问关系 ID

标签 node.js graphql nestjs typeorm

我正在设置一个利用 TypeORM 的 NestJS GraphQL API,但在实现实体之间的关系时遇到问题。

具体来说,TypeORM 关系运行良好,并且实体在数据库中链接正确。然而,当我尝试查询 API 来获取结果时,问题就出现了。

现在我有 2 个实体,每个实体都有自己的解析器:用户和照片。每个用户可以拥有多张照片,而每张照片只能连接到一个用户(多对一)。

以下是实体与 TypeORM 的链接方式

照片实体,与用户实体有关系

@ManyToOne(type => User, user => user.photos, {
    onDelete: 'CASCADE',
})
@JoinColumn()
user: User;

用户实体,完成与照片实体的连接

@OneToMany(type => Photo, photo => photo.user, {
    eager: true,
})
photos: Photo[];

此代码有效,让我们检索用户的照片

用户解析器

@ResolveProperty('photos')
async photos(@Parent() user): Promise<Photo[]> {
    return await this.service.readPhotos(user.id);
}

用户服务

async readPhotos(userId): Promise<Photo[]> {
    return await this.photoRepository.find({
        where: {
            user: userId
        }
    });
}

* 请注意,photoRepository 可以通过“用户”字段进行过滤。 *

但是,此代码不起作用。它应该让我们查看哪个用户连接到了照片,而不是返回 null。

照片解析器

@ResolveProperty('user')
async user(@Parent() photo): Promise<User> {
    console.log(photo);
    return await this.service.readUser(photo.user);
}

此照片解析器似乎包含该问题;控制台输出的照片对象表明,虽然 @Parent 照片对象具有所有可用的静态字段(如 ID、发布日期、URL),但由于某种原因,此处无法访问实际的“用户”字段。因此“photo.user”变量为空。 * 请注意,这似乎表明 photoRepository 无法被“用户”字段过滤/访问。 *

照片服务

async readUser(userId): Promise<User> {
    return await this.userRepository.findOne({
        where: {
            user: userId
        }
    });
}

由于之前的照片解析器无法访问“用户”字段,因此 userId 为空,因此返回 null。

结论

为什么照片解析器无法访问 @Parent 照片“用户”字段?用户服务似乎能够很好地按“用户”字段进行过滤,但我似乎无法直接访问照片“用户”字段。

感谢您对此提供的任何帮助!这两天我一直被这个问题难住了......

最佳答案

所以您想访问该用户,是吗? 照片.用户?在 FindOptions 中,有一个名为“relations”的键,它将为您获取并应用该键。所以在你的例子中

async readPhotos(userId): Promise<Photo[]> {
    return await this.photoRepository.find({
        where: {
            user: userId
        },
        relations: ['user'],
    });
}

现在应该是photo.user。另一种方法是相反的

async readUser(userId): Promise<User> {
    return await this.userRepository.findOne({
        where: {
            user: userId
        },
        relations: ['photos'],
    });
}

现在应该以 Photo 数组的形式返回 user.photos

您可以在此处找到更多 FindOptions 用法示例 http://typeorm.io/#/find-options

希望这有帮助!

关于node.js - 如何从 NestJS/TypeORM 中父级的连接字段访问关系 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54163467/

相关文章:

postgresql - 迁移文件中的 NestJS TypeORM 语法错误

javascript - root id 中没有呈现任何内容

以列表作为参数变量的 Golang Mutation (GRAPHQL)

javascript - apollo graphql 突变 - JSON 输入意外结束

vue.js - graphql-标签/加载器 : Module build failed with GraphQLError: Syntax Error

github - 如何使用 nestjs 进行 github 社交登录?

node.js - 错误: Nest cannot export component/module that is not a part of the currently processed module (DatabaseModule)

javascript - jQuery,查找触发事件元素的选择器

node.js - 错误 : Cannot find module '/app/__sapper__/build' on Cloud Build

javascript - `Fatal error: Unable to find local grunt.` : why asking for local grunt, 如果我有全局?