问题
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'
})
}
}
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;
}
回答1:
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: this operation will update all the data of meta that has user = :id
来源:https://stackoverflow.com/questions/65907844/update-a-column-in-database-in-nodejs