Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeORM When updating a specific column, save without affecting UpdateDateColumn

Tags:

typeorm

I want to save without affecting UpdateDateColumn when updating view column.

This table is a post table and the view is a hit.


UpdateDateColumn is updated when adding the number of view Column.
I don't want the view column to affect UpdateDateColumn.
@Entity("post")
export default class Post extends BaseEntity {
  @PrimaryGeneratedColumn()
  idx: number;

  // Skip
  
  @Column({
    nullable: false,
    default: 0
  })
  view: number;

  @Column("timestampz")
  @CreateDateColumn()
  created_at: Date;

  @Column("timestampz")
  @UpdateDateColumn()
  updated_at: Date;
}

Give me a solution please.

like image 743
Sh031224 Avatar asked Jul 21 '20 04:07

Sh031224


People also ask

How to add created_at column in typeorm?

In TypeORM, you can add a created_at column and a updated_at column by making use of the CreateDateColumn and UpdateDateColumn decorators, respectively. These columns will be automatically initialized and updated to the current date and time (that is, the current timestamp).

Why does typeoorm serialize the timestamp and timestamp to strings?

Because of that, TypeoORM serializes them to strings, even though it seems to cause confusion. TypeORM works differently with the timestamp and timestamp with timezone columns. In contrast to the time and date columns, the timestamp data time contains everything needed to create a Date object.

How to update the primary column in the database?

The workaround is first do .findOne () and then do .save () if it didn't' find an account. Example is the second code block in the question above. If it can help people who face the same problem, i think that .save () will perform an update in case the primary column (id in this case) is precised and exists in database.


1 Answers

Not a perfect solution, but still a solution...

You can force update your date column with the value it has:

getRepository(Post).update(postId, {
  view: newViewValue,
  updated_at: () => '"updated_at"'
})

The SQL-query will look like:

UPDATE "post" SET "view" = $2, "updated_at" = "updated_at" WHERE "idx" = $1
like image 140
alexhutsau Avatar answered Nov 15 '22 10:11

alexhutsau