How To Use Embedding To Get Data From A Table

Viewed 95

I am a PHP programmer and I have just learned Golang for weeks. I am writing REST API to get post information from my 'posts' table. I have the FindPostByID method in posts_controller. This controller uses Post struct which is model

func (p *Post) FindPostByID(db *gorm.DB, pid uint64) (*Post, error) {
    var err error
    err = db.Debug().Model(&Post{}).Where("id = ?", pid).Take(&p).Error
    if err != nil {
        return &Post{}, err
    }
    if p.ID != 0 {
        err = db.Debug().Model(&User{}).Where("id = ?", p.AuthorID).Take(&p.Author).Error
        if err != nil {
            return &Post{}, err
        }
    }
    return p, nil
}

But now I want to add method FindByID into parent struct, such as ParentModel because when I have articles_controller I can use FindByID method in parent struct to get an article info. So I have the following code in parent struct

type ParentModel struct {
    
}

func (m *ParentModel) FindByID(db *gorm.DB, uid uint64) (*ParentModel, error) {
    var err error
    err = db.Debug().Model(ParentModel{}).Where("id = ?", uid).Take(&m).Error
    if err != nil {
        return &ParentModel{}, err
    }
    if gorm.IsRecordNotFoundError(err) {
        return &ParentModel{}, errors.New("User Not Found")
    }
    return m, err
}

And I change in the Post struct like following:

type Post struct {
    ParentModel
    ID        uint64    `gorm:"primary_key;auto_increment" json:"id"`
    Title     string    `gorm:"size:255;not null;unique" json:"title"`
    Content   string    `gorm:"size:255;not null;" json:"content"`
    Author    User      `json:"author"`
    AuthorID  uint32    `sql:"type:int REFERENCES users(id)" json:"author_id"`
    CreatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"created_at"`
    UpdatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"updated_at"`
}

I change FindPostByID method in posts_controller as well:

func (server *Server) GetPost(w http.ResponseWriter, r *http.Request) {

    vars := mux.Vars(r)
    pid, err := strconv.ParseUint(vars["id"], 10, 64)
    if err != nil {
        responses.ERROR(w, http.StatusBadRequest, err)
        return
    }
    post := models.Post{}

    postReceived, err := post.FindByID(server.DB, pid)
    if err != nil {
        responses.ERROR(w, http.StatusInternalServerError, err)
        return
    }
    responses.JSON(w, http.StatusOK, postReceived)
}

When I run my program, have the err: Table 'golang_rest_api.parent_models' doesn't exist.

How I can do to use inheritance method like PHP language

1 Answers

The error Table 'golang_rest_api.parent_models' doesn't exist means that no table named parent_models exists in your database.

This is because gorm by default uses the pluralised camelcase name of your struct, which you supplied in gorm's Model() method, as its table's name.

Gorm provides in-built support for many kinds of associations which you can find here. I would also like to ask you to complete your ParentModel struct's definition. It's empty right now.

Related