V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
conight
V2EX  ›  Go 编程语言

Gorm 使用的问题

  •  
  •   conight · 2020-09-24 17:16:00 +08:00 · 948 次点击
    这是一个创建于 1315 天前的主题,其中的信息可能已经有所发展或是发生改变。

    现在有俩个表

    type A struct {
    	...
    }
    
    type B struct {
    	...
    	AID string `gorm:"column:a_id;not null;"`
    	...
    }
    

    B 表中有 AID 。 现在实现了以下 SQL

        select a.*,
           (
               select count(*)
               from b
               where b.a_id = a.id
           ) as b_count
        from a
    

    Gorm

    	db = db.Select(`a.*, (
               select count(*)
               from b
               where b.a_id = a.id
           ) as b_count`)
    

    A 表中没有 b_count 字段,所以关联不上。这个要怎么实现。

    先谢谢各位好兄弟

    rimutuyuan
        1
    rimutuyuan  
       2020-09-24 17:27:53 +08:00
    使用 db.Exec 执行原生 sql

    或者添加 foreignKey 使用关联
    conight
        2
    conight  
    OP
       2020-09-24 17:44:35 +08:00
    @rimutuyuan 执行 SQL 需要再定义一个新的 struct
    使用 foreignKey 的话多条记录绑定也需要新的定义么?
    conight
        3
    conight  
    OP
       2020-09-24 17:54:32 +08:00
    已解决
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1061 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 23:51 · PVG 07:51 · LAX 16:51 · JFK 19:51
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.