Supabase 更新并递增数值

huangapple go评论55阅读模式
英文:

Supabase update with incrementing value

问题

我正在使用supabase-js,并且有一个类似这样的表:

userID: 字符串
timesVisited: 数字
eventName: 字符串

我正在使用以下方式进行更新:

Admin.from(tableName).update([{userID,eventName,timesVisited}])

目前我必须进行两次调用,一次获取当前timesViewed,然后更新它。我想知道是否有一种方法可以直接增加该值,而不是进行两次调用?

英文:

I am using supabase-js and have a table like this:

userID: string
timesVisited: number
eventName: string

I am using update like this:

Admin.from(tableName).update([{userID,eventName,timesVisited}])

Currently I have to make two calls one to get current timesViewed and then update it I was interested in knowing if there's a way I could directly increment the value instead of making 2 calls?

答案1

得分: 3

你可以使用 Postgres 函数和 supabase-js 库的 .rpc 方法来实现这个。在SQL编辑器中创建一个函数:

create function increment (x int, row_id int) 
returns void as
$$
  update table_name 
  set column_name = column_name + x
  where id = row_id
$$ 
language sql volatile;

然后像这样调用它:

const { data, error } = await supabase
  .rpc('increment', { x: 1, row_id: 2 })
英文:

You would do this using a Postgres function and the .rpc method of the supabase-js library.

Create a function using the SQL editor

create function increment (x int, row_id int) 
returns void as
$$
  update table_name 
  set column_name = column_name + x
  where id = row_id
$$ 
language sql volatile;

And call it like:

const { data, error } = await supabase
  .rpc('increment', { x: 1, row_id: 2 })

huangapple
  • 本文由 发表于 2023年5月7日 13:57:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76192402.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定