Where communities thrive

  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
Repo info
  • 16:02
    alexeykureev assigned #5368
  • 16:02
    alexeykureev labeled #5368
  • 16:02
    alexeykureev opened #5368
  • 14:07
    github-actions[bot] labeled #5352
  • 14:07
    github-actions[bot] commented #5352
  • 13:53
    github-actions[bot] unlabeled #5352
  • 13:32
    Emptyless commented #5352
  • 13:07
    a631807682 commented #75
  • 13:05
    a631807682 synchronize #75
  • 10:52
    zetaab commented #5330
  • 10:09
    ophum opened #5367
  • 09:33
    januwA commented #5364
  • 08:44
    zetaab commented #5330
  • 08:39
    zetaab commented #5330
  • 08:38
    zetaab commented #5330
  • 08:38
    zetaab commented #5330
  • 08:35
    zetaab commented #5330
  • 08:20
    zetaab commented #5330
  • 08:17
    zetaab commented #5330
  • 07:12
    dependabot[bot] labeled #5366
is that behaviour still available somewhere in the new gorm?
Tim Newsham
Hi. I'm using gorm with postgresql. I need to use several separate databases on the same postgresql server instance. I found info online saying I can use db.Table(...) to select a db for queries and updates. I am having trouble finding info on how to select different DBs for migrations (ideally with db.Automigrate). How can I do this?
3 replies
I am attempting migrating to gorm version 2. Models that have other fields of models or fields of model slices are being attempted to select from. Is there a way to disable this behavior globally?
Florian Ritterhoff

Hey all, I'm currently trying to do some more complex queries (filtered LEFT JOINS) using gorm. Sadly it seems like I have to build these queries using Raw statements. What I'm a little bit wondering is, that I have to do some additional Preloading.


delegated := []model.Domain{}

err := s.db.Raw("SELECT * FROM domains LEFT JOIN delegations ON delegations.domain_id = domains.id AND delegations.deleted_at IS NULL WHERE (delegations.user = ? OR domains.owner = ?) AND domains.deleted_at IS NULL", owner, owner).Find(&delegated).Error

Does not provide me the nested list, even it is actually returned by the query.

I use gorm2 0 batch insert data, use callback function to modify created On field, but only the created of the first data in the array On has been modified, and the value of other data in this field is zero
This message was deleted
Hi, how I can use custom ENUM for gorm model field type?
1 reply
Is it possible to create all the tables and then go back and create all the foreign keys? Calling db.Migrator().CreateTable(...) still tries to create the foreign keys and AutoMigrate(...) can't seem to handle circular foreign key references.
can you marshal gorm.Model into JSON somehow?
time.Time doesn't really work and I can't use a custom type
Sujit Baniya
With Gorm on Postgres bytea data (slice of string), I'm not able to pull data from db to struct. It just return empty data
Any idea of the issue? Why such issue is happening?
Hello Everyone, Please I need help..
I have been unable to get past this error " can't preload field UserID for service.Address "

type Address struct {
ID int64 json:"id"
UserID User gorm:"association_foreignkey:user_id"
UserId int gorm:"column:user_id" // Guest users may place an order, so they should be able to create an address with nullable UserId
StreetAddress string json:"street_address"
City string json:"city"
Country string json:"country"
Postal string json:"postal"
State string json:"state"
CreatedAt time.Time json:"created_at"
UpdatedAt time.Time json:"updated_at"
// DeletedAt time.Time json:"deleted_at"
FirstName string json:"first_name"
LastName string json:"last_name"
Orders []Order gorm:"foreignKey:AddressId"

func (s Content) FetchAddressesPage(userId int, page int64, pageSize int64, includeUser bool) (address []Address, totalAddressesCount int) {

address = []Address{}

fmt.Print("value of the addressses\n", address)

s.dbc.Model(&address).Where(&Address{UserId: userId}).Count(&totalAddressesCount)
// s.dbc.Where(&Address{UserId: userId}).
//     Offset((page - 1) * pageSize).Limit(pageSize).
//     Preload("UserID"). // doesn't works fine(try Joins but lookup error)
//     Find(&address)

err := s.dbc.Where(&Address{UserId: userId}).
    Offset((page - 1) * pageSize).Limit(pageSize).Preload("UserID").
    // doesn't works fine(try Joins but lookup error)

The user's table

type User struct {
// json.Model
ID int json:"id"
FirstName string json:"first_name"
LastName string json:"last_name"
Username string json:"username"
Email string json:"email"
Password string json:"password"

// Comments []Comment `json:"foreignkey:UserId"`
Comments []Comment `json:"comment"`
// Roles     []Role    `json:"many2many:users_roles;"`
Roles []Role `json:"roles"`
// UserRoles []UserRole `json:"foreignkey:UserId"`
UserRoles []UserRole `json:":user_roles"`


I am not sure what I am getting wrong..
Hey there nis a way to change the schema in the connection?
I am building a multitwnant app
Matti Lundgren

Hello! Is it possible to get time.Time in the timezone of the selected column? I am using gorm with Clickhouse and doing a query on the form of:

select date_trunc('day', date, 'Europe/Stockholm') from table_name;

which returns the date truncated correctly however gorm returns it in UTC instead of Europe/Stockholm. The time is correct but it would help a lot to get it in the timezone used in date_trunc :)

Sandeep Nambiar
hey! i am trying to setup a backend that reads a json configuration for the data it needs to serve and sets up the sql tables based on the config. I've been using raw sql to configure/read/write the tables. I am wondering if it is possible to use gorm for this with dynamic models. I am not sure how to begin with that.
Nikhil Vasudev
can any one help me to execute following query using jinzhu gorm package
SELECT queries into @sql FROM trade_signal.queries;
prepare query from @sql;
execute query;
hello, is it possible to update the primary key as part of auto migrate? I have a composite primary key and I would like to mark another attribute as primary key. on redeploying i dont see in the db schema the field as part of the primary as it should be
Enes Furkan Olcay
Hi, is it possible to get returning rows with CreateInBatches method? When i use Scan method , it makes an another select query
Do we have a guide document to make contribute to gorm
Hi, I'm trying to build an audit plugin for Postgres. I'm following this post https://stackoverflow.com/a/64872879/1684235, but it fails when I'm trying to insert (.Save(log)) with "sql: Scan error on column index 0, name "id": unsupported Scan, storing driver.Value type int64 into type *Log". It seems like .Save() respects a point to store the Id of the main record and not a point to the NEW Log record to insert. Any ideas?
1 reply
Hello all. I'm trying to pluck a column from a grouped query, and then use that column in a where clause, and I can't quite seem to figure out how to structure my code to do so. I have a table full of historical data, where the highest ID is the most current. Could anyone offer some advice on how to manage that?
Michael Nussbaum
Hello, is it possible to create an inner join using Gorm without writing SQL strings? As far as I can tell the normal db.Model(aModel).Join("ARelation, db.Where(aRelationWithFieldsSet) yields a left outer join against the relation, so the conditions in the where clause are ignored. I'd like to be able to join only against rows that meet a certain condition
1 reply

type u1 struct {
OrderNo string json:"orderNo" gorm:"uniqueIndex:idx_order_no;comment:ddd"
Name string json:"name" comment:"名称" validate:"required"
Urs []ur1 json:"urs" gorm:"foreignkey:UId;references:ID"
type ur1 struct {
UId uint json:"uId" gorm:"uniqueIndex:idx_uid;comment:ddd"
R r1 json:"r" gorm:"foreignkey:UrId;references:ID"
Desc string json:"desc"
type r1 struct {
UrId uint json:"urId" gorm:"uniqueIndex:idx_urid;comment:ddd"
Name string json:"name" comment:"名称"

func TestEnableMysql21(t *testing.T) {
db, err := datasource.EnableMysql2(module.MysqlConf{
Address: "",
Username: "test2",
Password: "123456",
DbName: "test2",
Prefix: "",
MaxOpenConns: 1,
MaxIdleConns: 1,
ConnMaxLifetime: 10,
IsLogMode: true,
NotReplace: true,
OrderNo: "1",
Name: "gy",
Urs: []ur1{
R: r1{
Name: "r1",
Desc: "urdesc",
db.Clauses(clause.OnConflict{UpdateAll: true}).Create(&u)
first time sql:
INSERT INTO r1 (created_at,updated_at,deleted_at,ur_id,name) VALUES ('2022-04-13 10:23:48.598','2022-04-13 10:23:48.598',NULL,5,'r1') ON DUPLICATE KEY UPDATE ur_id=VALUES(ur_id)
INSERT INTO ur1 (created_at,updated_at,deleted_at,uid,desc) VALUES ('2022-04-13 10:23:48.598','2022-04-13 10:23:48.598',NULL,5,'urdesc') ON DUPLICATE KEY UPDATE uid=VALUES(uid)
INSERT INTO u1 (created_at,updated_at,deleted_at,order_no,name) VALUES ('2022-04-13 10:23:48.597','2022-04-13 10:23:48.597',NULL,'1','gy') ON DUPLICATE KEY UPDATE updated_at='2022-04-13 10:23:48.597',deleted_at=VALUES(deleted_at),order_no=VALUES(order_no),name=VALUES(name)
but second time sql: I want update all r1 ur_id = 0
INSERT INTO r1 (created_at,updated_at,deleted_at,ur_id,name) VALUES ('2022-04-13 10:24:40.518','2022-04-13 10:24:40.518',NULL,0,'r1') ON DUPLICATE KEY UPDATE ur_id=VALUES(ur_id)

INSERT INTO ur1 (created_at,updated_at,deleted_at,uid,desc) VALUES ('2022-04-13 10:24:40.517','2022-04-13 10:24:40.517',NULL,5,'urdesc') ON DUPLICATE KEY UPDATE uid=VALUES(uid)

INSERT INTO u1 (created_at,updated_at,deleted_at,order_no,name) VALUES ('2022-04-13 10:24:40.517','2022-04-13 10:24:40.517',NULL,'1','gy') ON DUPLICATE KEY UPDATE updated_at='2022-04-13 10:24:40.517',deleted_at=VALUES(deleted_at),order_no=VALUES(order_no),name=VALUES(name)

Excuse me, what is this question
Kay Khan
How do i pass multiple params to .Raw(statement, arg1, arg2) when my args is a slice/list
.Raw(statement, argSlice...)
postgresql 使用gorm v2自动迁移数据表报错
2022/04/24 15:40:51 D:/Developement/go/pkg/mod/gorm.io/driver/postgres@v1.3.3/migrator.go:432
[1.000ms] [rows:-] SELECT a.attname as column_name, format_type(a.atttypid, a.atttypmod) AS data_type
FROM pg_attribute a JOIN pg_class b ON a.attrelid = b.relfilenode AND relnamespace = (SELECT oid FROM pg_catalog.pg_namespace WHERE nspname = CURRENT_SCHEMA())
WHERE a.attnum > 0 -- hide internal columns
AND NOT a.attisdropped -- hide deleted columns
AND b.relname = 'bikes'
fieldColumnType====+{SQLColumnType:<nil> NameValue:{String: Valid:false} DataTypeValue:{String: Valid:false} ColumnTypeValue:{String: Valid:false} PrimaryKeyValue:{Bool:false Valid:false} UniqueValue:{Bool:false Valid:false} AutoI
ncrementValue:{Bool:false Valid:false} LengthValue:{Int64:0 Valid:false} DecimalSizeValue:{Int64:0 Valid:false} ScaleValue:{Int64:0 Valid:false} NullableValue:{Bool:false Valid:false} ScanTypeValue:<nil> CommentValue:{String: Valid:false} DefaultValueValue:{String: Valid:false}}ct {<nil> { false} { false} { false} {false false} {false false} {false false} {0 false} {0 false} {0 false} {false false} <nil> { false} { false}}
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xc0000005 code=0x0 addr=0x28 pc=0x8b5a96]

goroutine 1 [running]:
gorm.io/gorm/migrator.ColumnType.DatabaseTypeName(0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, ...)
D:/Developement/go/pkg/mod/gorm.io/gorm@v1.23.4/migrator/column_type.go:46 +0x126
gorm.io/driver/postgres.Migrator.AlterColumn.func1.1(0xc00009bda0, 0x1965ee0, 0xc000040150)
D:/Developement/go/pkg/mod/gorm.io/driver/postgres@v1.3.3/migrator.go:253 +0x10d
gorm.io/gorm.(*DB).Connection(0xc000130de0, 0xc000665098, 0x0, 0x0)
D:/Developement/go/pkg/mod/gorm.io/gorm@v1.23.4/finisher_api.go:539 +0x167
gorm.io/driver/postgres.Migrator.AlterColumn.func1(0xc00012a700, 0x153b2e0, 0xc0000ae000)
D:/Developement/go/pkg/mod/gorm.io/gorm@v1.23.4/migrator/migrator.go:101 +0x26e
gorm.io/gorm.(*DB).AutoMigrate(0xc0004348d0, 0xc0002be190, 0x1, 0x1, 0x0, 0x0)
D:/Developement/go/pkg/mod/gorm.io/gorm@v1.23.4/migrator.go:28 +0x64
D:/Developement/go/src/bicycle/api/main.go:64 +0x3c7
exit status 2
make: *** [Makefile:21: run] Error 1
why clause.Assignments sort columns
anyone know why?
Shailesh Birari
Has anyone tried combination of raw sql and explicit transactions with gorm v2 + prepared statements?
Shailesh Birari
Also, is there perf comparison between gorm v1 and gorm v2?
Anyone know of an alternative to qor admin for Gormv2?
just wonder anybody can point me to a piece of code ( in golang/porn ) which will generate two tables related with a foreign key constrain ? thx
Witold Baryluk
Hi. Exploring my options for state management in an Go app I am making. Are there some options to use Gorm with with some embedded db in Go? I guess sqlite would work probably, but any other options? Something like bolt or badger would be nice (yeah, they don't have SQL layer and no built in secondary indexes, but maybe somebody is working on something similar?).
Witold Baryluk
Are there any monitoring metrics in the gORM that I can track? I.e. total count of transactions, committed txs, rolledback (i.e. explicit or via panic/error) txs, aborted txs due to a conflict, number of scanned rows per table, number of scans per table (or query template), average cardinality, count of errors by operation and type (i.e. SQL parsing errors counts from the backend), etc.
1 reply
Hello, I am a student in Korea. I'm asking because I have a question that I'm really curious about. When using preload in gorm, it works with where in, but if it is received by in, there is a phenomenon that it is not received if it exceeds 1000 pieces. Is there any other way around this? MariaDB is in use. I think it will be too complicated if I take out the preload. I want to know how to get data even if I use more than 1000 pieces. thank you.
I am looking for a good example of dynamically creating has many entries in a nested struct

Does anyone know how to deal with struct in struct with gorm? A example is,

type A struct{
     ID int,
    b B
type B struct{
    ID int,
    name string,

How can I query A from database, and the filed 'b' is filled with actual B?