【问题标题】:gorm how to foreign self戈尔姆如何外国自我
【发布时间】:2016-10-19 05:51:43
【问题描述】:

例如:

type User struct {
    gorm.Model
    BestFriend User
}

我想要BestFriend字段外来相同的用户模型,如何用golang gorm包定义这个。

谢谢。

【问题讨论】:

    标签: go go-gorm


    【解决方案1】:

    http://jinzhu.me/gorm/associations.html

    type Profile struct {
        gorm.Model
        Name string
    }
    
    type User struct {
        gorm.Model
        Profile      Profile `gorm:"ForeignKey:ProfileRefer"` // use ProfileRefer as foreign key
        ProfileRefer int
    }
    

    或使用其他方式

    类似的东西……你试过了吗?

    type User struct {
        gorm.Model
        UserId int
        Username string
        BestFriend int
    }
    
    func GetUser(id int) User {
       //select * from users where UserId = id
    }
    

    【讨论】:

    • 我不明白你的做法。你能更清楚地解释一下吗?
    • 你不能做递归类型...你会收到无效的递归类型用户
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-08
    • 2016-04-14
    • 1970-01-01
    • 2010-09-18
    • 2014-08-31
    • 2022-01-16
    • 1970-01-01
    相关资源
    最近更新 更多