查询具有条件的多对多关系

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

Querying Many to Many with Conditions

问题

我有一个类似这样的gorm many2many模型:

type User struct {
    gorm.Model
    Username    string  
    LikedBooks []Books `gorm:"many2many:user_liked_books;"`
}

type Book struct {
    gorm.Model
    Name        string 
    Likes       []User `gorm:"many2many:user_liked_books;"`
}

其中一个User可以喜欢多本Book,而一本Book可以有多个喜欢它的User
现在我想查询被喜欢的书籍,并返回前50本被喜欢的书籍。
我该如何使用gorm实现这个功能?我不明白如何在book.liked = true的条件下进行查询,按喜欢的数量排序,并限制为50本。
我在文档或stackoverflow上找不到类似的示例。

英文:

I have a gorm many2many model like this:

type User struct {
	gorm.Model
	Username    string  
	LikedBooks []Books `gorm:"many2many:user_liked_books;"`
}

type Book struct {
	gorm.Model
	Name        string 
	Likes       []User `gorm:"many2many:user_liked_books;"`
}

Where a User can like many Books and a Book can have many Users that like it.
I now want to query for Books that have been liked, and return the top 50 liked books.
How can I achieve that using gorm? I dont understand how to query with conditions on book.liked = true, sorted by liked count, limited by 50.
I couldnt find an example like that in the docs or on stackoverflow.

答案1

得分: 2

这可以通过使用gorm函数来构建与你描述的请求相同的SQL查询方式来完成。代码可能如下所示:

var books []Book
tx := db.Table("books").
      Joins("INNER JOIN user_liked_books ulb ON ulb.book_id = books.id").
      Select("books.id, books.name, count(ulb.user_id) as likes_count").
      Group("books.id, books.name").
      Order("likes_count desc").
      Limit(50).
      Find(&books)

如果你还想加载`Likes`字段可以尝试在上述代码中添加`.Preload("Likes")`
英文:

This could be done in the same way you would construct a SQL query for the request you described, just using the gorm functions. It could look something like this:

var books []Book
tx := db.Table("books").
      Joins("INNER JOIN user_liked_books ulb ON ulb.book_id = books.id").
      Select("books.id, books.name, count(ulb.user_id) as likes_count").
      Group("books.id, books.name").
      Order("likes_count desc").
      Limit(50).
      Find(&books)

If you would also want to load the Likes field, try adding .Preload("Likes") to the construct above.

huangapple
  • 本文由 发表于 2021年9月21日 04:22:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/69260382.html
匿名

发表评论

匿名网友

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

确定