简体   繁体   English

如何从 NestJS/TypeORM 中父的加入字段访问关系 ID

[英]How to access relationship ID from Parent's joined field in NestJS/TypeORM

I'm setting up a NestJS GraphQL API that utilizes TypeORM, and am having trouble implementing relationships between entities.我正在设置一个使用 TypeORM 的 NestJS GraphQL API,并且在实现实体之间的关系时遇到了问题。

Specifically, the TypeORM relationships are working great, and the entities are linking correctly in the database.具体来说,TypeORM 关系运行良好,实体在数据库中正确链接。 However, the problem comes in when I try to query the API to get the results.但是,当我尝试查询 API 以获取结果时,问题就出现了。

Right now I have 2 entities, each with their own resolver: Users and Photos.现在我有 2 个实体,每个实体都有自己的解析器:用户和照片。 Each User can have multiple Photos, while each Photo is only connected to one User (Many-to-One).每个用户可以拥有多张照片,而每张照片只连接到一个用户(多对一)。

Here's how the entities are linked with TypeORM以下是实体与 TypeORM 的链接方式

Photo Entity, with a relationship to the User Entity照片实体,与用户实体有关系

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

User Entity, completing connection to the Photo Entity用户实体,完成与照片实体的连接

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

This code works, and let's us retrieve a User's Photos此代码有效,让我们检索用户的照片

User resolver用户解析器

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

User service用户服务

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

* Note that the photoRepository is able to be filtered by the 'user' field. *请注意,photoRepository 可以通过“用户”字段进行过滤。 * *

This code, however, does not work.但是,此代码不起作用。 It should let us view which User is connected to the Photo, instead it returns null.它应该让我们查看哪个用户连接到照片,而不是返回 null。

Photo resolver照片解析器

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

This Photo resolver seems to contain the problem;此照片解析器似乎包含问题; the photo object being output by the console indicates that while the @Parent photo object has all of its static fields available (like the ID, datePublished, URL), for some reason the actual 'user' field is not accessible here.控制台输出的照片对象表明,虽然@Parent 照片对象的所有静态字段都可用(如 ID、datePublished、URL),但由于某种原因,此处无法访问实际的“用户”字段。 So the 'photo.user' variable is null.所以'photo.user' 变量为空。 * Note that this seems to indicated that the photoRepository is UNABLE to be filtered by/access the 'user' field. *请注意,这似乎表明 photoRepository 无法被“用户”字段过滤/访问。 * *

Photo service照片服务

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

This returns null since the userId is blank, due to the previous Photo resolver not being able to access the 'user' field.这将返回 null,因为 userId 为空,因为之前的照片解析器无法访问“用户”字段。

Conclusion结论

Why can't the Photo resolver access the @Parent photo 'user' field?为什么照片解析器无法访问@Parent 照片“用户”字段? The User service seems to be able to filter by the 'user' field just fine, yet I can't seem to be able to access the Photo 'user' field directly.用户服务似乎能够按“用户”字段进行过滤就好了,但我似乎无法直接访问照片“用户”字段。

Thank you for any help on this!感谢您对此的任何帮助! I've been stumped on this for the last two days...这两天一直在纠结这个。。。

So you'd like to access the user huh?所以你想访问用户是吧? photo.user ? photo.user In FindOptions there's a key called 'relations' this will fetch and apply that for you.FindOptions有一个名为“关系”的键,它将为您获取并应用它。 So in your example所以在你的例子中

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

This should now be photo.user .现在应该是photo.user Another way would be the reverse另一种方式是相反的

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

This should now return user.photos as an array of Photo s现在应该将user.photos作为Photo数组返回

You can find more examples of FindOptions usages here http://typeorm.io/#/find-options你可以在这里找到更多FindOptions用法的例子http://typeorm.io/#/find-options

Hope this helps!希望这可以帮助!

I was struggling with a similar problem and although @bashleigh's solution works if you want the entire entity returned I only needed the id.我正在为一个类似的问题而苦苦挣扎,虽然@bashleigh 的解决方案在您希望整个实体返回时有效,但我只需要 id。 So if that's your case you can pass the loadRelationIds option, and set it to true .因此,如果这是您的情况,您可以传递loadRelationIds选项,并将其设置为true

return await this.photoRepository.find({
 where: {
  id: photoId
 },
 loadRelationIds: true
});

This will return user as just the id (string or int).这将仅以 id(字符串或整数)的形式返回用户。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM