dsxmwin86342 2019-04-18 13:03
浏览 129

如何使用SQLBoiler执行多对多查询

I'm using SQLBoiler as my golang ORM.

I'm trying to query a user and all of his roles, to do that I have the following tables:

ROLES:

role_id  desc   name
1        basic  basic

USERS:

user_id password    user_name   created_at  updated_at  updated_by ...
1        ...        ...         ...         ...         ...  

USERS_ROLES:

id  user_id role_id
1   1       1
foreign keys: user_id, role_id

I'm trying to query (without using sql query) a user and all of his roles in the following way:

func getUserRoles(user *models.USERS) (models.USERROLESSlice, error) {
    if roles, err := user.UserUSERROLESS().All(context.Background(), DB); err != nil {
        infra.LogError("failed to query user roles", err)
        return nil, err
    } else {
        return roles, nil
    }
} 

which gives me models.USERROLESSlice instead of slice of models.ROLES that contain my joining table.

or to just use:

   if usr, err := models.USERSS(qm.Where(query, req.Email, req.Password),qm.Load("ROLES")).One(context.Background(), DB); err != nil && err.Error() == "sql: no rows in result set" {
        infra.LogInfo(fmt.Sprintf("no result for %s", req.Email))
        return nil, nil
    } 

as I would have done if I had any other object-relationship but non of those give me the result I expect.

any one know what is the easy & elegant way to do it?

Edit: For now I just used qm.SQL to get forward

    if roles, err := models.ROLESS(qm.SQL("SELECT roles.* FROM user_roles INNER JOIN roles ON user_roles.role_id = roles.role_id WHERE user_roles.user_id=@uid", user.UserID)).All(context.Background(), DB); err != nil {
    infra.LogError("failed to query user roles", err)
    return nil, err
}

but again I'm looking for the elegant way, you can find some examples in the following link: https://github.com/volatiletech/sqlboiler

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 winform的chart曲线生成时有凸起
    • ¥15 msix packaging tool打包问题
    • ¥15 finalshell节点的搭建代码和那个端口代码教程
    • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
    • ¥15 Centos / PETSc / PETGEM
    • ¥15 centos7.9 IPv6端口telnet和端口监控问题
    • ¥120 计算机网络的新校区组网设计
    • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
    • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
    • ¥20 海浪数据 南海地区海况数据,波浪数据