为了账号安全,请及时绑定邮箱和手机立即绑定

Golang 与 GORM。如何正确地将模型类型传递给方法?

Golang 与 GORM。如何正确地将模型类型传递给方法?

Go
偶然的你 2023-06-19 15:29:15
我有下一个 GORM 模型package entityimport (    "github.com/jinzhu/gorm")type InterfaceEntity interface {}type User struct {    InterfaceEntity    gorm.Model    Name string}我尝试将 GORM 实体类型传递到基础 crud 存储库中。我的基础 crud 存储库:package repositoryimport (    "billingo/model/entity"    "fmt"    "github.com/jinzhu/gorm"    "reflect")type CrudRepository struct {    *BaseRepository}func NewCrudRepository(db *gorm.DB) CrudRepositoryInterface {    repo := NewBaseRepository(db).(*BaseRepository)    return &CrudRepository{repo}}func (c CrudRepository) Find(id uint, item entity.InterfaceEntity) entity.InterfaceEntity {    fmt.Println("--- Initial")    var local entity.User    fmt.Println("--- local: ", reflect.TypeOf(local), local)    fmt.Println("--- Item:  ", reflect.TypeOf(item), item)    fmt.Println("--- Values")    c.db.First(&local, id)    fmt.Println("--- local: ", reflect.TypeOf(local), local)    c.db.First(&item, id)    fmt.Println("--- Item: ", reflect.TypeOf(item), item)    return item}正如您在这里看到的,方法中有item和local变量Find()。我item通过服务的下一种方式传递:func (c CrudService) GetItem(id uint) entity.InterfaceEntity {    var item entity.User    return c.repository.Find(id, item)}看来whatlocal和item必须是equals和behavior必须是等价的。但是输出是--- Initial--- local:  entity.User {<nil> {0 0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC <nil>} }--- Item:   entity.User {<nil> {0 0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC <nil>} }--- Values--- local:  entity.User {<nil> {1 0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC <nil>} test 1}--- Item:  entity.User {<nil> {0 0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC <nil>} }INFO[0000] User info                                     user="{<nil> {0 0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC <nil>} }" user-id=1(/home/mnv/go/src/billingo/model/repository/CrudRepository.go:29) [2019-05-17 17:07:37]  unsupported destination, should be slice or struct item从服务传递到消息不支持的目标,应该是 slice 或 struct如何item正确通过,我需要像 with 这样的行为local?
查看完整描述

2 回答

?
墨色风雨

TA贡献1853条经验 获得超6个赞

Gorm 不想将数据解组为您的空接口类型。

即使您传递的是实现该特定接口的结构,它在传递后仍保持类型化为接口。您需要将该item接口转换回您的User结构。

喜欢item.(entity.User)


查看完整回答
反对 回复 2023-06-19
?
素胚勾勒不出你

TA贡献1827条经验 获得超9个赞

哦,我已经修好了。


现在Find从服务调用存储库方法&item:


func (c CrudService) GetItem(id uint) entity.InterfaceEntity {

    var item entity.User

    return c.repository.Find(id, &item)

}

存储库方法item不通过&:


func (c CrudRepository) Find(id uint, item entity.InterfaceEntity) entity.InterfaceEntity {

    c.db.First(item, id)

    return item

}


查看完整回答
反对 回复 2023-06-19
  • 2 回答
  • 0 关注
  • 72 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信