dongmaobeng7145 2018-07-17 08:42
浏览 102

带有外键的模型上的restful api

TLDR; How to create REST api on model having Foreign key (or db relationship in general) in buffalo framework?

I am absolute beginner in go and I am trying to write an RESTFul service using buffalo framework following following example given on it official website. I am able to create RESTful api on models which have no database relationship. But I am stuck when I faced a situation where model has a foreign key. I am not able to find any documentation or reference on web. I concept on Go is also weak, you can also educate me on those thins.

Models: (ref: https://gobuffalo.io/en/docs/db/relations#example

type Composer struct {
    ID              uuid.UUID `json:"id" db:"id"`
    Name            string    `json:"name" db:"name"`
    Description     string    `json:"description" db:"description"`
    CreatedAt       time.Time `json:"created_at" db:"created_at"`
    UpdatedAt       time.Time `json:"updated_at" db:"updated_at"`

}


type Track struct {
    ID          uuid.UUID           `json:"id" db:"id"`
    Title       string              `json:"title" db:"title"`
    Description string              `json:"description" db:"description"`
    Composer    Composer            `has_one:"composer" fk_id:"id"`
    CreatedAt   time.Time           `json:"created_at" db:"created_at"`
    UpdatedAt   time.Time           `json:"updated_at" db:"updated_at"`
}

Resources: (ref: https://gobuffalo.io/en/docs/resources)

type TrackResource struct {
    buffalo.Resource
}


func (v TrackResource) List(c buffalo.Context) error {
    tx, ok := c.Value("tx").(*pop.Connection)
    if !ok {
        return errors.WithStack(errors.New("no transaction found"))
    }

    pieces := &models.Tracks{}

    q := tx.PaginateFromParams(c.Params())

    if err := q.All(pieces); err != nil {
        return errors.WithStack(err)
    }

    c.Set("pagination", q.Paginator)

    return c.Render(200, r.JSON(pieces))
}


func (v TrackResource) Show(c buffalo.Context) error {
    tx, ok := c.Value("tx").(*pop.Connection)
    if !ok {
        return errors.WithStack(errors.New("no transaction found"))
    }

    piece := &models.Track{}

    if err := tx.Find(piece, c.Param("track_id")); err != nil {
        return c.Render(404, r.JSON(err))
    }

    return c.Render(200, r.JSON(piece))
}


func (v TrackResource) Create(c buffalo.Context) error {

    piece := &models.Track{}

    if err := c.Bind(piece); err != nil {
        return errors.WithStack(err)
    }

    tx, ok := c.Value("tx").(*pop.Connection)
    if !ok {
        return errors.WithStack(errors.New("no transaction found"))
    }

    verrs, err := piece.Create(tx)
    if err != nil {
        return errors.WithStack(err)
    }

    if verrs.HasAny() {
        return c.Render(422, r.JSON(verrs))
    }

    return c.Render(201, r.Auto(c, piece))
}


func (v TrackResource) Update(c buffalo.Context) error {

    tx, ok := c.Value("tx").(*pop.Connection)
    if !ok {
        return errors.WithStack(errors.New("no transaction found"))
    }

    piece := &models.Track{}

    if err := tx.Find(piece, c.Param("track_id")); err != nil {
        return c.Error(404, err)
    }

    if err := c.Bind(piece); err != nil {
        return errors.WithStack(err)
    }

    verrs, err := piece.Update(tx)
    if err != nil {
        return errors.WithStack(err)
    }

    if verrs.HasAny() {
        return c.Render(422, r.JSON(verrs))
    }

    return c.Render(200, r.JSON(piece))
}


func (v TrackResource) Destroy(c buffalo.Context) error {

    tx, ok := c.Value("tx").(*pop.Connection)
    if !ok {
        return errors.WithStack(errors.New("no transaction found"))
    }

    piece := &models.Track{}

    if err := tx.Find(piece, c.Param("track_id")); err != nil {
        return c.Error(404, err)
    }

    if err := tx.Destroy(piece); err != nil {
        return errors.WithStack(err)
    }

    return c.Render(200, r.JSON(piece))
}

When I am trying to create a track. I am getting error:

json: cannot unmarshal string into Go struct field Track.Composer of type models.Composer
gitlab.com/****/****/actions.TrackResource.Create

enter image description here

Please help.

  • 写回答

2条回答 默认 最新

  • douzhanrun0497 2018-07-17 09:43
    关注

    You're trying to bind a Track containing a Composer with its ID, but Composer is defined as a struct.

    To make it work, you need to implement the Unmarshaler interface and define how to convert this ID into the Composer struct you want.

    评论

报告相同问题?

悬赏问题

  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP