问题描述
我想更新一个有关系的列:
I want to update a column which has a relation:
async update(req, res): Promise<any> {
const {email, password, id} = req.body;
try {
await getConnection()
.createQueryBuilder()
.update(User)
.set({
email: email,
password: password,
meta: [{
name: "tesst",
message: "jasshd"
}]
})
.where("id = :id", {id: id})
.execute();
res.status(201).send({
message: 'user updated'
})
} catch (e) {
console.log('update', e)
res.send({
message: 'update error'
})
}
}
元表与用户表有关.尝试使用附加的元更新用户,我得到: EntityColumnNotFound: No entity column "meta";找到了.
.为什么我收到这个错误?注意:如果我在注册用户时使用这种关系,例如:
Meta table is in relation with User table.Trying to update the user with the attached meta i get: EntityColumnNotFound: No entity column "meta" was found.
. Why i get this error? Note: If i use this relation when i register the user like:
const user = this.usersRepository.create({
email,
password,
meta: [{
name: "tesst",
message: "jasshd"
}]
});
return await this.usersRepository.save(user);
...代码有效.为什么代码在我注册用户时有效,但在我更新时无效?
... the code work. Why the code works when i register the user but not when i update it?
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column({nullable: true})
email: string;
@Column({nullable: true})
password: string;
@OneToMany(() => Meta, meta => meta.user, { cascade: true })
meta: Meta[];
}
export class Meta {
@PrimaryGeneratedColumn({name: metaId})
metaId: number;
@Column({nullable: true})
name: string;
@Column({nullable: true})
message: string;
@ManyToOne(() => User, user => user.meta)
user: User;
}
推荐答案
我不认为你可以用 querybuilder 更新关系数据,我在这里看到的解决方案是用自身更新 meta
:
I don't think you can update the relation data with querybuilder, the solution I see here is to update meta
with itself :
async update(req, res): Promise<any> {
const {email, password, id} = req.body;
try {
await getConnection()
.createQueryBuilder()
.update(User)
.set({
email: email,
password: password,
meta: [{
name: "tesst",
message: "jasshd"
}]
})
.where("id = :id", {id: id})
.execute();
// Update meta :
await getConnection()
.createQueryBuilder()
.update(Meta)
.set({
name: "tesst",
message: "jasshd"
})
.where("user = :id", {id: id})
.execute();
res.status(201).send({
message: 'user updated'
})
} catch (e) {
console.log('update', e)
res.send({
message: 'update error'
})
}
}
Ps:此操作将更新所有具有user = :id
这篇关于在 NodeJs 中更新数据库中的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!