我有一张看起来像这样的桌子
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从填充的表中分配外键? 谢谢您的帮助!
答案 0 :(得分:0)
所以出现错误是因为在Hobby
类中,我根据需要拥有members
。无论这是不是一个好主意,我都不是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.
希望这会在将来对其他人有所帮助。