by

Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
  • 17:17
    github-actions[bot] closed #3262
  • 17:05
    github-actions[bot] closed #3261
  • 15:17
    github-actions[bot] closed #3260
  • 12:26
    github-actions[bot] labeled #3270
  • 12:26
    botastic assigned #3270
  • 12:26
    botastic opened #3270
  • 12:23
    botastic opened #71
  • 09:25
    pielambr edited #3269
  • 09:21
    github-actions[bot] labeled #3269
  • 09:20
    pielambr assigned #3269
  • 09:20
    pielambr opened #3269
  • 09:16
    pielambr opened #70
  • 07:29
    github-actions[bot] labeled #3268
  • 07:29
    Molecular-Future assigned #3268
  • 07:29
    Molecular-Future opened #3268
  • 05:44
    mitar commented #66
  • 05:44
    mitar commented #65
  • 04:14
    itsursujit closed #68
  • 04:04
    Kisesy commented #3256
  • 03:53
    github-actions[bot] closed #3256
Sujit Prasad Baniya
@itsursujit
In v1, I could do something like this:
func SetupDB() (*gorm.DB, error) {
    LoadDBConfig()
    if DB != nil {
        return DB, nil
    }
    connectionString := DBConfig.DB_User + ":" + DBConfig.DB_Pass + "@tcp(" + DBConfig.DB_Host + ")/" + DBConfig.DB_Name + "?charset=utf8&parseTime=True&loc=Local" //nolint:wsl,lll
    var err error                                                                                                                                                   //nolint:wsl

    // Connect again with DB name.
    DB, err = gorm.Open(DBConfig.DB_Driver, connectionString)
    if err != nil {
        return nil, err
    }

    DB.DB().SetMaxOpenConns(100)
    DB.DB().SetMaxIdleConns(100)
    DB.DB().SetConnMaxLifetime(5 * time.Minute)
    return DB, nil //nolint:wsl
}
ZZY2357
@ZZY2357
func findPostByID(id string) (postFound Post, err error) {
    var post Post
    db.First(&post, "ID = ?", id)
    if post.Title != "" {
        return post, nil
    }
    return post, errors.New("Post not found")
}
It cannot set post.ID into id
ZZY2357
@ZZY2357
Is it the mistake of the type?
Or my mind?
ZZY2357
@ZZY2357
I also create another table users
yeluoqiuzhi
@yeluoqiuzhi
hello, is anyone here?
Thanks, Who can help me solve this? go-gorm/gorm#1236
yeluoqiuzhi
@yeluoqiuzhi
哈哈哈
yeluoqiuzhi
@yeluoqiuzhi
<script>console.log('hello')</script>
monsterpooka
@monsterpooka
I try to save a big.Int value into mysql, but it seem gorm ignore this. so what I need to do?
Alex Walker
@amlwwalker

Hi, I have created a relationship between a campaign and a []customers. I can create an entry in the psql db and attach customers when I db.Save() however how do I add relationships later when my frontend sends the ID of the campaign and the IDs of the customers.
I have tried:

func UpdateCustomersForCampaignByIds(cId uint, ids []uint) error {
    var c Campaign
    if err := db.Debug().Where("id=?", cId).Preload("Customers", "id IN (?)", ids).Update(&c).Error; err != nil {
        return err
    }
    return nil
}

however I get nothing entered into the foreign-key table when I call it with

customerIds := []uint{1}
database.UpdateCustomersForCampaignByIds(4, customerIds)

Thanks!

ChannelCook
@ChannelCook
Is there anybody tell me diffrent between gorm:"not null" and sql:"not null"?
vojta001
@vojta001

Could anyone just point me to the right direction or tell me it is not possible? I use simple preloads with

db.Preload("Countries").Find(&towns)

It works great. However, I would like to do the same using JOINs, instead of SELECT and then SELECT WHERE IN. Is it possible? I found out GORM isn't willing to load fields of the inner struct (Country in this case) without having it mentioned in the Preload, however it always makes a SELECT WHERE IN if you include it in the Preload, no matter what other columns have already been selected

Jeroen Bulters
@bulters
Hi!
I'm running into an error I cant figure out: Trying to append an item to a many2many relation via db.Model(&parent).Association("Remarks").Append(newRemark)
but it gives me a glorious invalid memory address or nil pointer dereference runtime error.
in this case the Remarks struct field is set to []MeetingRemark
and many2many tag is setup correctly (since the Preload works as expected)
Morteza Aghili
@MortezaAghili
Hi there!
Do you have any working Gin & Gorm example that has Many2Many? I'm stuck in implemented relations!
Best
qilx
@qilx
Which package should I use: github.com/jinzhu/gorm or gorm.io/gorm? It seems like firstone should be older v1 and second v2. But I can`t find dialects for second one. And also documentation for both v1 and v2 mentions first package.
rookie7799
@rookie7799
howdy, is it possible to print the final query before executing it ?
Tom Berger
@tab1293
yes, in gorm v2 use a logger with logger.Info log level http://v2.gorm.io/docs/logger.html
rookie7799
@rookie7799
right, that I see but is there a "standalone" func that I can call ?
Tom Berger
@tab1293
@qilx connecting with v2 is documented here: https://github.com/go-gorm/gorm/wiki/GORM-V2-Release-Note-Draft#usage and docs are here http://v2.gorm.io/docs/
rookie7799
@rookie7799
having hard time creating multiple compound indexes
type UserClassmate struct {
ID int64 gorm:"primary_key" json:"id"
EduID1 int64 json:"exp_id1" gorm:"index:edu1;index:edu1_user1;index:edu1_user2"
EduID2 int64 json:"exp_id2" gorm:"index:edu2;index:edu2_user1;index:edu2_user2"
UserID1 int64 json:"user_id1" gorm:"index:user_id1;index:edu1_user1;index:edu2_user1"
UserID2 int64 json:"user_id2" gorm:"index:user_id2;index:edu1_user2;index:edu2_user2"
but when running "create tables" i get
CREATE INDEX edu1_user2 ON user_classmate(edu_id1) [] 0
CREATE INDEX edu2_user2 ON user_classmate(edu_id2, user_id2) [] 0
CREATE INDEX edu2_user1 ON user_classmate(user_id1) [] 0
which makes no sense
qilx
@qilx
@tab1293 Thank you!
jjvsun
@jjvsun
How to use gorm second-level cache
ahuigo
@ahuigo
Is there any good way to make gorm support postgresql's array type?
{"message":"sql: converting argument $1 type: unsupported type []string, a slice of string"}
ahuigo
@ahuigo
Gorm supports custom any type of data. e.g. Array
struct Room{
    names pq.StringArray ` gorm:"type:text[]"`
}
Sujit Prasad Baniya
@itsursujit
Is there any example of connection pooling and settings for MaxOpenConnections and Idle Connection on Gorm v2?

I'm wondering how this piece of code:

sqlDB, err := DB.DB()
    sqlDB.SetMaxOpenConns(100)
    sqlDB.SetMaxIdleConns(100)
    sqlDB.SetConnMaxLifetime(5 * time.Minute)
return DB, nil

will ensure the MaxOpenConnections and IdleConnection on DB.DB() because the settings are defined for sqlDB which is a new variable

Sujit Prasad Baniya
@itsursujit

I tried to implement GormV2 with SetMaxOpenConns and SetMaxIdleConns using following code

var DB *gorm.DB

func SetupDB() (*gorm.DB, error) {
    //nolint:wsl,lll
    var err error //nolint:wsl
    LoadDBConfig()
    connectionString := ""
    if DB != nil {
        return DB, nil
    }
    switch DBConfig.DB_Driver {
    case "postgres":
        connectionString = fmt.Sprintf("host=%s port=%d user=%s dbname=%s password=%s", DBConfig.DB_Host, DBConfig.DB_Port, DBConfig.DB_User, DBConfig.DB_Name, DBConfig.DB_Pass)
        DB, err = gorm.Open(postgres.Open(connectionString), &gorm.Config{})

    default:
        connectionString = fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local", DBConfig.DB_User, DBConfig.DB_Pass, DBConfig.DB_Host, DBConfig.DB_Port, DBConfig.DB_Name)
        DB, err = gorm.Open(mysql.Open(connectionString), &gorm.Config{})
    }
    if err != nil {
        panic(err)
    }
    sqlDB, err := DB.DB()
    sqlDB.SetMaxOpenConns(100)
    sqlDB.SetMaxIdleConns(100)
    sqlDB.SetConnMaxLifetime(5 * time.Minute)
    return DB, nil //nolint:wsl
}

func GetUserByEmail(email string) (*User, error) {
    var user User
    if err := DB.Where(&User{Email: email}).First(&user).Error; err != nil {
        return nil, err
    }
    return &user, nil //nolint:wsl
}

Getting following error when trying to do a load test:

failed to connect to `host=localhost user=postgres database=casbin`: server error (FATAL: sorry, too many clients already (SQLSTATE 53300))

What am I missing in above code?

wengang.liu
@Nihility981
hello anyone here
not v2.0 how batch insert data
@jinzhu
and i need this data id
wengang.liu
@Nihility981
a century later
Joshua Hemmings
@jLemmings

What am I doing wrong while trying to preload data?
db.Debug().Preload("Disposal").Where("project_id = ?", c.Param("id")).Find(&projects)

My Project model:

// Project struct is used to store all relevant information
type Project struct {
    ProjectID uint   `gorm:"primary_key" json:"ProjectID"`
    Name      string `json:"Name"`
    Disposals []Disposal
    Supplies  []Supply
}

My Disposal model:

// Disposal struct is used to store all relevant information
type Disposal struct {
    DisposalID      uint       `gorm:"primary_key" json:"DisposalID"`
    Depository      Depository `gorm:"foreignkey:DepositoryRefer" json:"Depository"`
    DepositoryRefer uint
    Material        Material `gorm:"foreignkey:MaterialRefer" json:"Material"`
    MaterialRefer   uint
    Date            time.Time `json:"Date"`
    Measurement     float64   `json:"Measurement"`
    Project         Project   `gorm:"foreignkey:ProjectRefer;AssociationForeignKey:project_id" json:"Project"`
    ProjectRefer    uint
}

The foreign keys I've set:

db.Model(Disposal{}).AddForeignKey("depository_refer", "depositories(depository_id)", "RESTRICT", "RESTRICT")
        db.Model(Disposal{}).AddForeignKey("material_refer", "materials(material_id)", "RESTRICT", "RESTRICT")
        db.Model(Disposal{}).AddForeignKey("project_refer", "projects(project_id)", "RESTRICT", "RESTRICT")
Philip Hutchins
@phutchins

Are there known issues with using associations? I have had a lot of trouble getting GORM to create associations consistently.

Also, is there a standard or guide as to when we would need to create associations as pointers vs not? Does adding a json tag affect an association?

Philip Hutchins
@phutchins
Separately, is there a way to select the entry in a set of results with the max value?
Akshit Dhar
@goakshit
Hi, I am new to GORM. I have been exploring GORM v2 for few days. I am stuck with table joins. db.Debug().Table("profile"). Joins("JOIN address ON address.uid = profile.uid"). Where("profile.uid = ?", uid). Find(&profileStruct) This query returns only fields belonging to the profile table, although i am expecting fields from both tables. Any help will be really appreciated. Thank you.
Kevin Smith
@kevinms_gitlab

Is it possible to do an unscoped preload? When I try:

db.Unscoped().Preload("Orders").Find(&users)

The Find() query is properly unscoped but the Preload() is not. The preload query still contains:

"orders"."deleted_at" IS NULL
karthik reddy
@karthikeya.44_gitlab
In gorm is there any way to manage cascade soft delete for associations? Seems with Soft delete we couldn't manage consistent associations. Do we have any option for it?
Alex Howarth
@alexhowarth
Best practice if I want to have lowercase json attributes for gorm.Model is to copy it and add the tags?
Jeremy Potter
@jwinnie_gitlab
This channel is full of questions but no answers haha