首页 > 解决方案 > TYPEORM 设置 fk 为 1:m / m:1

问题描述

我有一张看起来像这样的桌子

Table: hobbies
----------------------------------------
id | name
----------------------------------------
1  | chess
2  | skydiving
________________________________________

然后每当有人注册并添加一个爱好时(为了简单起见,他们只能有一个爱好并确保这不是 M:M)

Table: Users
------------------
id|   name    | hobbyId
------------------
1 |Christian  | NULL

这是我实现它的方式:

export async function addNewUser(userData: UserInformation): ServerReponse {
// userData = { name: "john", hobby: "skydiving" }
const hobbyRepo = getManager().getRepository('hobbies');
const hobbyId = await hobbyRepository.findOne({name: userData.hobby}) // hobbyId = { id: 2, name 'skydiving' }
const user = new User();
user.name = userData.name
user.hobby = hobbyId //user.hobby is underlined in red*
  try {
    await getManager().save(user);
  } catch(e){} //no error

我得到的 user.hobby 的错误是Type '{}' is missing the following properties from type 'Specialty': id, name, membersts(2739)

实体:用户

@Entity('users')
export class User {

  @PrimaryGeneratedColumn()
  public id: number;

  @Column()
  public name: string;

  @ManyToOne(type => Hobby, specialty => specialty.members)
  public hobby: Hobby;
}

实体:爱好

@Entity('hobbies')
export class Hobby {
  @PrimaryGeneratedColumn()
  public id: number;

  @Column()
  public name: string;

  @OneToMany(type => User, user => user.hobby)
  public members: User[];
}

使用 typeorm 如何从填充的表中分配外键?谢谢您的帮助!

标签: typescriptmariadbtypeorm

解决方案


所以错误来了,因为在Hobbymembers所要求的课程中。如果这是一个好主意,我不是 100%,但是,我把它变成了可选的:

@OneToMany(type => User, user => user.specialy)
@JoinColomn()
public members?: User[] | User | null;

同样在 model.ts 文件中,我现在将其作为:

const hobbyFk = await hobbyRepository.findOne({name: userData.hobby});
user.name = userData.name;
user.hobby = hobbyFk as HobbyInterface; //HobbyInterface is one I created.
with that above I was able to correctly set the fk.

希望这将在未来对其他人有所帮助。


推荐阅读