带有关系 ID 的 Typeorm 插入 [英] Typeorm insert with relationId

查看:78
本文介绍了带有关系 ID 的 Typeorm 插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Typeorm,我只想使用 relationId 插入一行.但它并没有像我预期的那样工作.

I use Typeorm, and simply I want to insert a row by using relationId. But it's not working as I expected.

这是我的实体,

@Entity()
export default class Address extends BaseEntity {

    @Column({
        type: 'varchar',
        length: 255,
    })
    public title: number;

    @Column({
        type: 'varchar',
        length: 2000,
    })
    public value: number;

    @ManyToOne(type => User, user => user)
    @JoinColumn({ name: 'userId' })
    public user: User;

    @RelationId((address: Address) => address.user)
    public userId: number;

}

当我尝试像下面的示例那样添加时,它添加了我不希望的空用户 ID

When I try to add like the below example, it adds null userId which I do not expect

{
    "title": "My home address",
    "value": "Lorep Ipsum Sit Amet",
    "userId": 4
}

当我更改有效负载时,一切正常.

When I change the payload, everything works perfectly.

{
    "title": "Ev adresim",
    "value": "Nova Suites",
    "user": 4
}

我不想使用像上面那样的负载.我沉迷于定义一个描述性的变量命名.感谢从现在开始的所有贡献和所有回答.

I do not want to use a payload like the above. I addicted to define a descriptive variable naming. Thanks for all contribution and all answer from now.

推荐答案

看起来这是 @RelationId 装饰器的 TypeORM 问题:https://github.com/typeorm/typeorm/issues/3867.

It looks like this is a TypeORM issue with the @RelationId decorator: https://github.com/typeorm/typeorm/issues/3867.

你可以用@Column来装饰userId而不是使用@RelationId,当JoinColumn的名称等于数字列名称时,TypeORM匹配两者,你可以设置userId或用户和TypeORM将处理它:

Instead of using @RelationId you can decorate the userId with @Column, when the name of the JoinColumn is equal to the number column name, TypeORM matches both and you can either set the userId or the user and TypeORM will handle it:

@ManyToOne(type => User, user => user)
@JoinColumn({ name: 'userId' })
public user: User;

@Column()
public userId: number;

这篇关于带有关系 ID 的 Typeorm 插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆