【问题标题】:How to conditionally search data with many to many relationships with gorm如何有条件地搜索与gorm具有多对多关系的数据
【发布时间】:2021-05-05 03:05:29
【问题描述】:

我正在开发一个使用 gorm 管理报价的应用程序。 报价有多个标签。 当指定多个标签时,我想获取包含所有指定标签的引号。

这是我的数据模型。

type Quote struct {
    ID        uint      `gorm:"primary_key" json:"id"`
    CreatedAt time.Time `json:"created_at"`
    UpdatedAt time.Time `json:"updated_at"`
    Text      string    `json:"text"`
    Page      uint      `json:"page"`
    ISBN      string    `json:"isbn"`
    Tags      []Tag     `gorm:"many2many:quote_tags;" json:"tags"`
}

type Tag struct {
    ID        uint      `gorm:"primary_key" json:"id"`
    CreatedAt time.Time `json:"created_at"`
    Name      string    `json:"name"`
}

我想做这样的事情。 (语法不正确)

db.Preload("Tags").Where(<quotes.tags.name contains all tagNames>).Find(&quotes) // tagNames []string

有没有办法用 gorm 做到这一点? 提前谢谢你。

【问题讨论】:

    标签: go go-gorm


    【解决方案1】:

    在这种情况下,您必须首先找出您需要运行的 SQL 的外观。

    要获得与所有给定标签匹配的所有引号,您需要将引号表连接到一个子查询,该子查询计算每个引号匹配多少个标签,如下所示:

    SELECT * 
    FROM quotes 
    JOIN (
       SELECT quote_id, count(*) AS count
       FROM quote_tags qt JOIN tags t ON qt.tag_id = t.id
       WHERE t.name IN ('tag1', 'tag2', 'tag4')
       GROUP BY quote_id
    ) AS matched ON quote_id = quotes.id AND matched.count = 3
    

    一旦你有了它,你就试着在 Gorm 中这样说:

    requiredTags := []string{"tag1", "tag2", "tag3"}
    db.Preload("Tags").
        Joins(
            "JOIN (?) AS matched ON quote_id = quotes.id AND matched.count = ?",
            db.Select("quote_id, count(*) AS count").
                Table("quote_tags qt").
                Joins("JOIN tags t ON qt.tag_id = t.id").
                Where("t.name IN (?)", requiredTags).
                Group("quote_id"),
            len(requiredTags),
        ).
        Find(&quotes)
    

    见:GORM Advanced Query/From Subquery

    【讨论】:

    • 我收到了这个错误。 Request is failed: sql: converting argument $1 type: unsupported type gorm.DB, a struct[] SQL 和子查询都正常工作,所以我认为将子查询分配给 JOIN 子句有问题。
    • 您使用的是哪个版本的 gorm?确保它是最新的稳定版本(或至少 > 1.20,相当于 > 2.0)
    • 我使用的是旧版本的 gorm。我从 github.com/jinzhu/gorm v1.9.16 更新到 gorm.io/gorm v 1.21.9 并且上述错误消失了。感谢您的有用回答!
    猜你喜欢
    • 1970-01-01
    • 2014-07-06
    • 1970-01-01
    • 2015-12-23
    • 1970-01-01
    • 2012-10-01
    • 2016-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多