The pit of gorm associated query

Keywords: Go PHP

Background: Recently, I am learning golang, trying to rewrite the previous PHP project with go.
The table models involved are as follows:

// Article
type Topics struct {
    Id              int    `gorm:"primary_key"`
    Title           string `gorm:"not null"`
    Body            string `gorm:"not null"`
    UserId          int    `gorm:"not null"`
    CategoryId      int    `gorm:"not null"`
    Status          int    `gorm:"default:1"`
    CreatedAt       time.Time
    UpdatedAt       time.Time
    Category Categories    `gorm:"foreignkey:CategoryId"`
    User     Users         `gorm:"foreignkey:UserId"`
}
// user
type Users struct {
    Id                int    `gorm:"primary_key"`
    Name              string `gorm:"not null"`
    Email             string `gorm:"not null"`
    Password          string `gorm:"not null"`
    Avatar            string
    CreatedAt         time.Time
    UpdatedAt         time.Time
    LastActivedAt     time.Time
}
// classification
type Categories struct {
    Id          int        `gorm:"primary_key"`
    Name        string     `gorm:"not null"`
    Description string     `gorm:"not null"`
    PostCount   int
    CreatedAt   time.Time
    UpdatedAt   time.Time
}

First, find the relevant introduction of gorm official documents:
http://doc.gorm.io/associatio...

code V1:

func (Topics) TopicByID(id int) (*Topics, error) {
    db := DB()
    defer db.Close()

    var topic Topics

    // 1. 
    //result := db.Model(&topic).Where("id=?", id).Related(&topic.User)

    //2. 
    //db.Where("id=?", id).First(&topic)
    //result := db.Model(&topic).Related(&topic.User)
    
    if err := result.Error; err != nil {
        return &topic, err
    }

    if result.RecordNotFound() == true {
        return &topic, utils.Error("Article does not exist!")
    }

    return &topic, nil
}

The two forms of code are basically the results I found after Baidu. After some attempts, they all reported an error: (invalid association []).
Then I am considering whether there is a problem with my foreign key definition:

(no problem)

Continue Baidu, find The relevance of gorm . Among them:

Here the Reload method adds a second parameter, so check gorm's introduction to this method:

You can add the corresponding foreign key parameters, and the test is successful.

Final code (code V2):

func (Topics) TopicByID(id int) (*Topics, error) {
    db := DB()
    defer db.Close()

    var topic Topics

    db.Where("id=?", id).First(&topic)
    // Associated key code
    db.Model(&topic).Related(&topic.Category, "CategoryId")
    result := db.Model(&topic).Related(&topic.User, "UserId")

    //result := db.Where("id=?", id).Preload("Category").Preload("User").First(&topic)
    if err := result.Error; err != nil {
        return &topic, err
    }

    if result.RecordNotFound() == true {
        return &topic, utils.Error("Article does not exist!")
    }

    return &topic, nil
}

Note: the Preload method in the comment section is more convenient and concise.

Output result: / / contains the article content, the corresponding user information of the article, and the article classification information

{
6 Test topic 2 <p>who are you?</p> 1 3 0 0 0 0   1 2018-09-11 14:30:39 +0800 CST 2018-09-11 14:43:44 +0800 CST 
{3 Q & A please be friendly and help each other 0 0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC} 
{1 aurora test@mail.com 3ffd3de33d3c8bf09bf835d8f7f9b0e0 http://Local.beego.com/static/upload/2018/09/07/deep-cc.png Lala ~ burp b506cf029de29c626a1a27bc4d70f5b0 0 0 2018-08-28 15:56:39 + 0800 CST 2018-09-07 14:32:46 + 0800 CST 0001-01 00:00 + 0000 UTC}
}

Conclusion:

The content of the previous article has not been sorted out yet. Let's have a look

Posted by morphy on Sun, 03 Nov 2019 02:32:43 -0800