Skip to content

建议: 使用转换器支持模型数据类型转换问 #135

@frudder

Description

@frudder

**生成器生成代码. 在查询返回的时候 调用了生成了 convertXXX() 方法 **

 阅读源代码发现使用copier.Copy() 作数据复制, 但是存在手动转换ID主键的情况, uint64 -> string  
 我发现copier.CopyWithOption() 提供option 选项 可以定义转换器能否使用转为器完成
`ToString = copier.TypeConverter{
	SrcType: uint64(0),
	DstType: "",
	Fn: func(from interface{}) (interface{}, error) {
		if v, ok := from.(uint64); ok {
			return strconv.FormatUint(v, 10), nil
		}
		return from, nil
	},
}

type Book struct {
	ID uint64 `json:"id"`
	Name string `json:"name"`
}

type BookView struct {
	ID string `json:"id"`
	Name string `json:"name"`
}

if err := copier.CopyWithOption(&view, &book, copier.Option{IgnoreEmpty: true, Converters:[]copier.TypeConverter{ToString}}); err != nil {
    
}
`

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions