typeorm icon indicating copy to clipboard operation
typeorm copied to clipboard

Cannot perform update query because update values are not defined. Call \"qb.set(...)\" method to specify updated values.

Open rewebcan opened this issue 7 years ago • 10 comments

When I save post entity with survey it throws the error I mention. I checked for similar issues to fix it. But they didn't work. When I remove @JoinColumn({name: 'surveyId'}) at Post survey property, it works but doesn't save the survey entities id on post.surveyId.

Could you help me please?

Issue type:

[x ] question [ ] bug report [ ] feature request [ ] documentation issue

Database system/driver:

[ ] cordova [ ] mongodb [ ] mssql [x] mysql / mariadb [ ] oracle [ ] postgres [ ] cockroachdb [ ] sqlite [ ] sqljs [ ] react-native [ ] expo

TypeORM version:

[ ] latest [ ] @next [x] 0.2.18 (or put your version here)

Steps to reproduce or a small repository showing the problem:

Classic NestJS setup, here is my entities and service.

survey.entity.ts

@Entity('survey')
export class Survey extends AuditEntity {

    @PrimaryGeneratedColumn()
    id: number;

    @Column('varchar')
    option_1: string;

    @Column('int')
    option_1_count: number;

    @Column('varchar')
    option_2: string;

    @Column('int')
    option_2_count: number;

    @Column('varchar')
    option_3: string;

    @Column('int')
    option_3_count: number;

    @Column('varchar')
    option_4: string;

    @Column('int')
    option_4_count: number;

    @Column('int')
    total_count: number;

    @Column('bigint')
    expiredAt: number;
}

post.entity.ts

@Entity('post')
export class Post extends AuditEntity {

    @PrimaryGeneratedColumn()
    id: number;

    @Column('text')
    text: string;

    @Column('int')
    surveyId: number;

    @Column('tinyint')
    isReady: boolean;

    @Column('int')
    sectionId: number;

    @Column('int')
    customerId: number;

    @Column('bigint')
    viewCount: number;

    @Column('bigint')
    likeCount: number;

    @Column('bigint')
    commentCount: number;

    @Column('tinyint')
    isDeleted: number;

    @OneToOne(type => Survey, survey => survey.id, { cascade: true })
    @JoinColumn({ name: 'surveyId' })
    survey: Survey;

    @ManyToMany(type => Asset, { cascade: true })
    @JoinTable({ name: 'post_asset', joinColumns: [{ name: 'post' }], inverseJoinColumns: [{ name: 'asset' }] })
    assets: Asset[];

    @OneToOne(type => Customer)
    customer: Customer;

    @BeforeInsert()
    initializeDefaults() {
        this.likeCount = 0;
        this.viewCount = 0;
        this.commentCount = 0;
        this.isDeleted = 0;
    }
}

post.service.ts


   /**
     * Insert a Post with attributes
     * @param createPostDto
    */
    async insert(createPostDto: CreatePostDto): Promise<Post> {
        try {
            const createdPost = await getManager().transaction(async (entityManager) => {
                const post = Object.assign(new Post(), { ...createPostDto.post });
                if (createPostDto.attributes) {
                    if (createPostDto.attributes.survey) {
                        const surveyData = {
                            background: createPostDto.attributes.survey.background,
                        };
                        _.forEach(createPostDto.attributes.survey.options, (option, i) => {
                            surveyData['option_' + option.key] = option.value;
                        });
                        const survey = Object.assign(new Survey(), { ...surveyData });
                        post.survey = survey;
                    }
                    if (createPostDto.attributes.asset) {
                        const asset = Object.assign(new Asset(), { ...createPostDto.attributes.asset });
                        post.assets = [asset];
                    }
                }
                return await entityManager.save(post);
            });
            return createdPost;
        } catch (error) {
            throw new InternalServerErrorException(error.message);
        }
    }

service logs

query: START TRANSACTION
query: INSERT INTO `survey`(`createdAt`, `updatedAt`, `id`, `option_1`, `option_1_count`, `option_2`, `option_2_count`, `option_3`, `option_3_count`, `option_4`, `option_4_count`, `total_count`, `expiredAt`) VALUES (?, ?, DEFAULT, ?, DEFAULT, ?, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT) -- PARAMETERS: [1564404254749,1564404254749,"Hitler","Stalin"]
query: INSERT INTO `post`(`createdAt`, `updatedAt`, `id`, `text`, `surveyId`, `isReady`, `sectionId`, `customerId`, `viewCount`, `likeCount`, `commentCount`, `isDeleted`) VALUES (?, ?, DEFAULT, ?, DEFAULT, DEFAULT, ?, DEFAULT, ?, ?, ?, ?) -- PARAMETERS: [1564404254749,1564404254749,"Hitler mi, stalin mi?",2,0,0,0,0]
query: INSERT INTO `asset`(`createdAt`, `updatedAt`, `id`, `customerId`, `type`, `path`, `url`, `width`, `height`, `name`, `format`, `duration`, `frameCount`, `frameRate`, `extension`, `size`, `isDeleted`, `isReady`, `isFailed`) VALUES (?, ?, DEFAULT, DEFAULT, ?, DEFAULT, ?, ?, ?, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, ?, DEFAULT, ?) -- PARAMETERS: [1564404254749,1564404254749,"image","https://cdn.playzsocial.com/files/1.png",600,500,false,false]
query: INSERT INTO `post_asset`(`post`, `asset`) VALUES (?, ?) -- PARAMETERS: [33,29]
query: ROLLBACK

rewebcan avatar Jul 29 '19 13:07 rewebcan

@rewebcan did you ever find a solution

jtushman avatar Feb 06 '20 16:02 jtushman

I had the same issue. In my case i had this error because i tried to save a foreign key, pointing at a non existing table entry

ZOniimOx avatar Feb 13 '20 08:02 ZOniimOx

@jtushman no I didn't ..

rewebcan avatar Feb 13 '20 13:02 rewebcan

I fixed it. Another source for the problem is sending primary keys in values, for example:

this.categoryRepository.update(input.id, {
      name: input.name,
      slug: input.slug
      // we cannot send id here
})

tuliofaria avatar Sep 29 '20 13:09 tuliofaria

Hello guys i have the same problem and i dont know why:

Cannot perform update query because update values are not defined. Call "qb.set(...)" method to specify updated values Expected Behavior

UserEntity

import { Entity, PrimaryGeneratedColumn, Column, BeforeInsert, OneToMany } from "typeorm"; import { UserRole } from "./user.interface"; import { BlogEntryEntity } from "src/blog/model/blog-entry.entity";

@entity() export class UserEntity {

@PrimaryGeneratedColumn() id: number;

@Column() name: string;

@Column({ unique: true }) username: string;

@Column() email: string;

@Column({select: false}) password: string;

@Column({type: 'enum', enum: UserRole, default: UserRole.USER}) role: UserRole;

@Column({nullable: true}) profileImage: string;

@OneToMany(type => BlogEntryEntity, blogEntryEntity => blogEntryEntity.author) blogEntries: BlogEntryEntity[];

@BeforeInsert() emailToLowerCase() { this.email = this.email.toLowerCase(); } }

BlogEntryEntity

import { Entity, PrimaryGeneratedColumn, Column, BeforeUpdate, ManyToOne } from "typeorm"; import { UserEntity } from "src/user/models/user.entity";

@entity('blog_entry') export class BlogEntryEntity {

@PrimaryGeneratedColumn() id: number;

@Column() title: string;

@Column() slug: string;

@Column({default: ''}) description: string;

@Column({default: ''}) body: string;

@Column({type: 'timestamp', default: () => "CURRENT_TIMESTAMP"}) createdAt: Date;

@Column({type: 'timestamp', default: () => "CURRENT_TIMESTAMP"}) updatedAt: Date;

@BeforeUpdate() updateTimestamp() { this.updatedAt = new Date; }

@Column({default: 0}) likes: number;

@Column({nullable: true}) headerImage: string;

@Column({nullable: true}) publishedDate: Date;

@Column({nullable: true}) isPublished: boolean;

@ManyToOne(type => UserEntity, user => user.blogEntries) author: UserEntity; }

Mehdi-Benrefad avatar Sep 02 '21 13:09 Mehdi-Benrefad

Hello guys i have the same problem and i dont know why:

Cannot perform update query because update values are not defined. Call "qb.set(...)" method to specify updated values Expected Behavior

UserEntity

import { Entity, PrimaryGeneratedColumn, Column, BeforeInsert, OneToMany } from "typeorm"; import { UserRole } from "./user.interface"; import { BlogEntryEntity } from "src/blog/model/blog-entry.entity";

@entity() export class UserEntity {

@PrimaryGeneratedColumn() id: number;

@column() name: string;

@column({ unique: true }) username: string;

@column() email: string;

@column({select: false}) password: string;

@column({type: 'enum', enum: UserRole, default: UserRole.USER}) role: UserRole;

@column({nullable: true}) profileImage: string;

@OneToMany(type => BlogEntryEntity, blogEntryEntity => blogEntryEntity.author) blogEntries: BlogEntryEntity[];

@BeforeInsert() emailToLowerCase() { this.email = this.email.toLowerCase(); } }

BlogEntryEntity

import { Entity, PrimaryGeneratedColumn, Column, BeforeUpdate, ManyToOne } from "typeorm"; import { UserEntity } from "src/user/models/user.entity";

@entity('blog_entry') export class BlogEntryEntity {

@PrimaryGeneratedColumn() id: number;

@column() title: string;

@column() slug: string;

@column({default: ''}) description: string;

@column({default: ''}) body: string;

@column({type: 'timestamp', default: () => "CURRENT_TIMESTAMP"}) createdAt: Date;

@column({type: 'timestamp', default: () => "CURRENT_TIMESTAMP"}) updatedAt: Date;

@BeforeUpdate() updateTimestamp() { this.updatedAt = new Date; }

@column({default: 0}) likes: number;

@column({nullable: true}) headerImage: string;

@column({nullable: true}) publishedDate: Date;

@column({nullable: true}) isPublished: boolean;

@manytoone(type => UserEntity, user => user.blogEntries) author: UserEntity; }

Try check output of object that you are saving. I had a same issue and in my case there was a invalid foreign key value, I saw above someone else had a similar reason as mine.

aamirpinger avatar Sep 16 '21 12:09 aamirpinger

I encountered this exception when I did pass a nonempty property object in repo.update(id, properties) , but all fields in it are @Column({readonly: true}) columns.

This is likely to be a rather unique cause of the exception . I'm just leaving this for others' reference.

jokester avatar Dec 09 '21 12:12 jokester

Also getting this error but in a different context: https://github.com/typeorm/typeorm/issues/9742

Sid-Turner-Ellis avatar Jan 29 '23 11:01 Sid-Turner-Ellis

I had the same issue. In my case i had this error because i tried to save a foreign key, pointing at a non existing table entry

Dude ... I opened this issue like 5 times and only now I realize what this means. If you have multiple nested relations i.e. user -> posts -> comments you need to first insert a user, retrieve it, insert all posts, reference the user in the posts, etc.

ghost avatar Jan 06 '24 17:01 ghost

TypeORM has returned to active development after recently transitioning to new leadership (see related announcement).

As part of the new team's efforts to prioritise work on the project moving forward, it is necessary to clean up the backlog of stale issues.

🧹 This issue is being automatically closed because it has had no activity in the last 6 months. If you believe this issue is still relevant, feel free to comment below and the maintainers may reopen it. Thank you for your contribution.

github-actions[bot] avatar Sep 18 '25 17:09 github-actions[bot]