如何创建查询来检查数组是否包含值?golang gorm

bxfogqkk  于 2023-11-14  发布在  Go
关注(0)|答案(2)|浏览(219)

模型看起来是这样的:

  1. type Board struct {
  2. Id uint `gorm:"primaryKey;autoIncrement;unique" json:"id"`
  3. Owner uint `json:"owner"`
  4. Name string `json:"name"`
  5. Contributors datatypes.JSON `gorm:"type:jsonb" json:"contributors"`
  6. GeneratedLink string `gorm:"default:''" json:"generated_link"`
  7. Todos datatypes.JSON `gorm:"type:jsonb" json:"todos"`
  8. }

字符集
这是postgresql列中contributors value的样子:


的数据
以及如何查询,检查贡献者数组包含例如20?我试图这样做:database.DB.Where("contributors IN ?", 20).Find(&contBoards),但得到错误:ERROR: syntax error at or near "$1" (SQLSTATE 42601)
请任何想法,任何选项。P.S使用gorm,postgresql

z3yyvxxp

z3yyvxxp1#

您可以在WHERE子句中使用IN运算子来检查值是否符合值清单中的任何值。
IN需要一个显式值列表(或子查询)。
我已经为您的案例创建了一个示例场景,如下所示:

  1. contributors := []int{20, 25, 27}
  2. var tmp []string
  3. for _, v := range contributors {
  4. tmp = append(tmp, fmt.Sprint(v))
  5. }
  6. query := "SELECT * from table_name where contributors in (" + strings.Join(tmp, ",") + ")"

字符串

ANY使用数组。如果数组中已经有值的列表,这会很有用。
使用ANY运算符,您只能搜索一个值。

  1. select * from table_name where value = ANY(contributors);


如果要搜索多个值,则可以使用@>运算符。
@>是“包含”运算符。
为几种数据类型定义如下:
数组:http://www.postgresql.org/docs/current/static/functions-array.html
范围类型:http://www.postgresql.org/docs/current/static/functions-range.html
几何图形类型:http://www.postgresql.org/docs/current/static/functions-geometry.html
JSON(和JSONB):http://www.postgresql.org/docs/current/static/functions-json.html
为了更好地了解您可以参考此链接:Postgres: check if array field contains value?

展开查看全部
sh7euo9m

sh7euo9m2#

在GORM DOC中有一些例子。
db.Where(“name IN?",[]string{“jinzhu”,“jinzhu 2”}).查找(&users)

相关问题