如何使用 GORM 获得明显的结果

问题描述 投票:0回答:2

在 Go 中,我编写了一个查询来提供所有数据,但我只想获取 products.id 和 client.id 不同的数据。 我可以写什么明喻查询?

res := find.Model(&domain.Clients{}).
    Select ("products.id product_id, products.name product_name,"+
        " clients.id id, clients.name name, clients.logo, clients.address, "+
        "clients.business_id, clients.num_of_employee, clients.email, clients.sns_link, clients.phone").
    Joins("LEFT JOIN company_interests ON company_interests.client_id = clients.id").
    Joins("LEFT JOIN products ON products.id = company_interests.product_id").
    Where("products.id = ? ", productId).Find(&resp)
mysql sql go go-gorm
2个回答
3
投票

在Go中,当我写“Select Distinct”然后休息查询时,它在Go中无效。所以,我想到了使用“group by”编写查询。在Go中,“group by”语法可以通过“GROUP”语法来使用。所以,最后下面的查询对我来说效果很好。

res := find.Model(&domain.Clients{}).
    Select ("products.id product_id, products.name product_name,"+
        " clients.id id, clients.name name, clients.logo, clients.address, "+
        "clients.business_id, clients.num_of_employee, clients.email, clients.sns_link, clients.phone").
    Joins("LEFT JOIN company_interests ON company_interests.client_id = clients.id").
    Joins("LEFT JOIN products ON products.id = company_interests.product_id").
    Where("products.id = ? ", productId).
    Group("company_interests.client_id, company_interests.product_id" ).Find(&resp)

0
投票

对于我来说,我使用 gorm 来查询数据库,这是我的 SELECT DISTINCT ON 解决方案

tx := dbRepo.db tx = tx.Model(model.ChatMessage{}).Select(fmt.Sprintf("DISTINCT ON (chat_room_id) %s", fields)).Where(filters.Query(),filters.Values()...)

© www.soinside.com 2019 - 2024. All rights reserved.