buffalo pop 模型关联的小坑。
我们使用官网上的 一对一 模型说明例子来测试。
例子模型
type Head struct {
ID int `db:"id"`
BodyID int `db:"body_id"`
Body *Body `belongs_to:"body"`
}
type Body struct {
ID int `db:"id"`
Head Head `has_one:"head"`
Info string `db:"info"`
}
我们需要把这两个模型重构为Mysql表,很简单的两个表
根据规则默认表名,需要是模型名的复数形式
heads 表结构
字段名 | 类型 | 备注 |
---|---|---|
id | int | |
body_id | int | body主键 |
bodies 表结构
字段名 | 类型 | 备注 |
---|---|---|
id | int | |
info | varchar | 为了方便,增加的 |
创建
body := &models.Body{
Info:"测试Body",
Head:models.Head{},
}
err := tx.Eager().Create(body)
if err != nil{
log.Panic(err)
}
默认表名情况下很正常,调用Create() err 返回值直接为 nil 增加的数据也是正常的
模型修改
实现一个 TableName 方法。此方法返回一个 string 作为此模型的表名
type Body struct {
ID int `db:"id"`
Head Head `has_one:"head"`
Info string `db:"info"`
}
func (u Body) TableName() string {
return "wb_bodies"
}
type Head struct {
ID int `db:"id"`
BodyID int `db:"body_id"`
Body *Body `belongs_to:"body"`
}
func (u Head) TableName() string {
return "wb_heads"
}
修改Mysql数据库原来对应的表名
heads 表名 改为 wb_heads
bodies 表名改为 wb_bodies
创建
body := &models.Body{
Info:"测试Body1",
Head:models.Head{},
}
err := tx.Eager().Create(body)
if err != nil{
log.Panic(err)
}
但是这次创建就不会成功了!控制台会输出如下代码..
DEBU[2019-09-07T20:40:58+08:00] INSERT INTO `wb_bodies` (`info`) VALUES (:info)
DEBU[2019-09-07T20:40:58+08:00] INSERT INTO `wb_heads` (`body_id`) VALUES (:body_id)
2019/09/07 20:40:58 Error 1146: Table 'test.heads' doesn't exist
会有一句 Error 语句,此语句由于使用了 log.Panic 打印,会导致开启了 app.Use(popmw.Transaction(models.DB)) 的路由方法出错,并回退事务。如果我们屏蔽掉 log.Panic(err) (或改其他 log 方法)又能成功在数据库中成功增加数据。
目前只能判断 err 具体错误信息,是否是 Table 'test.heads' doesn't exist 如果不是再打印,回退事务。这应该是本身的缺陷,导致代码要多写句!有大佬去提 issues 么?我英语表达不行。
用中式英语去提issues也没有问题。人家能看懂。