typescript - 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 如何从填充的表中分配外键?谢谢您的帮助!
解决方案
所以错误来了,因为在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.
希望这将在未来对其他人有所帮助。
推荐阅读
- reactjs - 检查路线访问的最佳方法
- python - Selenium 找到了错误的元素,一个甚至不存在的元素
- c - 无法在C中打开二进制文件
- lisp - Common Lisp 在下行期间跟踪如何工作
- docker - 使用预设 Dockerize ESLint
- laravel - Laravel 混合观看模式下的无限重建循环
- laravel - Laravel:未定义变量:RoomTypes(查看:
- javascript - 如何从python发送正确的http响应?
- node.js - 我无法在 mongodb 中创建多个用户
- elasticsearch - 如何在基于字段的弹性搜索中获取唯一文档,并根据其他字段对结果进行“分组”