首页 > 解决方案 > 如何在 Buffalo 中执行原始 SQL?

问题描述

如何在Buffalo中执行原始 SQL 查询,而无需设置我自己的数据库连接sqlx

澄清一下:我中定义了我的数据库连接database.yml,但此时我不想使用 Pop 模型。

标签: gobuffalo

解决方案


您还可以使用 Pop 定义 RawQueries:https ://godoc.org/github.com/gobuffalo/pop#Connection.RawQuery

在您的 Buffalo 操作中,您可以执行以下操作:

func (v myResource) MyMethod(c buffalo.Context) error {
    // Get the DB connection from the context
    tx, ok := c.Value("tx").(*pop.Connection) // you get your connection here
    if !ok {
        return errors.WithStack(errors.New("no transaction found"))
    }
    q := tx.RawQuery("select * from foo where id = ?", 1) // you make your query here
    if err := q.All(model); err != nil {
        return errors.WithStack(err)
    }
}

这将是使用 Pop 而不是预定义模型的解决方案。在这种情况下,您只需使用 Buffalo 上下文附带的连接。


推荐阅读