如果数组中不存在整数,我正在尝试将整数添加到数组中。但以下创建重复值:
User.update(
{
'topics': sequelize.fn('array_append', sequelize.col('topics'), topicId),
},
{where: {uuid: id}})
PostgreSQL/sequelize 中是否有与 MongoDB $addToSet 等效的函数?
最佳答案
引用MongoDB Manual :
The $addToSet operator adds a value to an array unless the value is already present, in which case
$addToSet
does nothing to that array.
此 SQL 命令执行您的要求:
UPDATE "user"
SET topics = topics || topicId
WHERE uuid = id
AND NOT (topics @> ARRAY[topicId]);
@>
在这种情况下,数组包含运算符和 ||
数组到元素的连接。 Details in the manual here.
相关:
不适用于 null
值。在这种情况下,请考虑:array_position(topics, topicId) IS NULL
。见:
您可以将它包装成一个简单的函数:
CREATE OR REPLACE FUNCTION f_array_append_uniq (anyarray, anyelement)
RETURNS anyarray
LANGUAGE sql IMMUTABLE PARALLEL SAFE AS
'SELECT CASE WHEN array_position($1,$2) IS NULL THEN $1 || $2 ELSE $1 END;'
像这样使用它:
...
SET topics = f_array_append_uniq (topics, topicId)
...
但是如果列值实际发生变化,顶部的查询甚至只会写入新的行版本。实现相同(无功能):
UPDATE "user"
SET topics = topics || topicId
WHERE uuid = id
AND array_position(topics,topicId) IS NOT NULL;
最后一个是我最喜欢的。
参见:
关于arrays - 添加数组元素(如果尚未包含),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48652374/