Gorm V1与V2的区别

huangapple go评论90阅读模式
英文:

Gorm V1 vs V2 differences

问题

有人能解释一下使用方言的 Gorm v1 和 Gorm v2 之间的区别吗?
我一直在重用之前项目中的代码,该代码使用 Gorm v1,其中通过从 dsn.Hostname 查询方言 gorm.GetDialect(),然后通过 gorm.RegisterDialect() 应用它。
在 Gorm 2 中没有这些方法,我对这些方法的作用感到困惑。
看起来如果这些方法已被移除,那么我们也不需要它们了,对吗?

英文:

Can anyone explain the difference between Gorm v1 and Gorm v2 using dialects?
I've been reusing code from the previous project, which worked with Gorm v1, where it was querying the dialect gorm.GetDialect() from dsn.Hostname, and applying it via gorm.RegisterDialect().
There are no such methods in Gorm 2, and I'm puzzled about what these are for anyways.
Seems that if these has been removed, then we don't need them anyways, right?

答案1

得分: 2

对于 Gorm V2,数据库连接的代码已更改为:

import (
  "gorm.io/driver/postgres"
  "gorm.io/gorm"
)

dsn := "host=localhost user=gorm password=gorm dbname=gorm port=9920 sslmode=disable TimeZone=Asia/Shanghai"
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})

gorm.Open 的代码根据 dialector 初始化了数据库会话,而现在已被 gorm.RegisterDialect() 替代。

// Open initialize db session based on dialector
func Open(dialector Dialector, opts ...Option) (db *DB, err error) {
    config := &Config{}

有关更多 V2 API 的详细信息,请参阅 https://gorm.io/docs/

英文:

For Gorm V2, the DB connection is changed to

import (
  "gorm.io/driver/postgres"
  "gorm.io/gorm"
)

dsn := "host=localhost user=gorm password=gorm dbname=gorm port=9920 sslmode=disable TimeZone=Asia/Shanghai"
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})

The code of gorm.Open initialize db session based on dialector, which is replaced with gorm.RegisterDialect()

// Open initialize db session based on dialector
func Open(dialector Dialector, opts ...Option) (db *DB, err error) {
	config := &Config{}

More V2 API details please refer to https://gorm.io/docs/

huangapple
  • 本文由 发表于 2022年10月13日 20:29:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/74055813.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定