英文:
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 Book
s and a Book
can have many User
s 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论