Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
  • 16:03
    dependabot[bot] labeled #58
  • 16:03
    dependabot[bot] labeled #58
  • 16:03
    dependabot[bot] opened #58
  • 16:03

    dependabot[bot] on go_modules

    Bump github.com/mattn/go-sqlite… (compare)

  • 15:02
    github-actions[bot] labeled #4792
  • 15:02
    github-actions[bot] commented #4792
  • 14:51
    github-actions[bot] unlabeled #4792
  • 14:47
    longlihale commented #4792
  • 13:21
    github-actions[bot] labeled #4792
  • 13:21
    github-actions[bot] commented #4792
  • 13:16
    enzofoucaud edited #4792
  • 13:12
    github-actions[bot] labeled #4792
  • 13:11
    enzofoucaud assigned #4792
  • 13:11
    enzofoucaud opened #4792
  • 13:09
    mint3u opened #49
  • 13:02
    enzofoucaud commented #4765
  • 12:53
    enzofoucaud commented #4765
  • 12:53
    enzofoucaud commented #4765
  • 12:15
    github-actions[bot] labeled #4791
  • 12:15
    github-actions[bot] commented #4791
CRThaze
@crthaze:matrix.org
[m]
Assuming I'm following everything right here
drpym
@drpym
you are :)
once i started stepping through after nullstring comment i found the issue and the only thing changed was that interface.
CRThaze
@crthaze:matrix.org
[m]
👍
Cesc
@cesc1802
hello, how can i setup relations to Preload with composite key

type CompanyAttribute struct {
model.BaseModel
Code string gorm:"column:code;primaryKey"
CompanyId uint64 gorm:"column:company_id;primaryKey"
ValueString string gorm:"column:value_string"
ValueInt
int gorm:"column:value_integer"
ValueDecimal decimal.Decimal gorm:"column:value_decimal;type:decimal(20, 5)"
ValueDatetime
time.Time gorm:"column:value_datetime"
ValueBoolean *bool gorm:"column:value_boolean;type:boolean"
AttrValues []CompanyAttributeValue gorm:"ForeignKey:Code,CompanyId;References:AttrCode,CompanyId"
}

func (CompanyAttribute) TableName() string {
return "company_attrs"
}

type CompanyAttributeValue struct {
ID uint64 gorm:"column:id;primaryKey"
AttrCode string gorm:"column:attr_code;not null"
CompanyId uint64 gorm:"column:company_id;not null"
ValueString string gorm:"column:value_string"
ValueInt
int gorm:"column:value_integer"
ValueDecimal decimal.Decimal gorm:"column:value_decimal;type:decimal(20, 5)"
ValueDatetime
time.Time gorm:"column:value_datetime"
ValueBoolean bool gorm:"column:value_boolean;type:boolean"
Weight
int gorm:"column:weight"
}

func (c CompanyAttributeValue) TableName() string {
return "company_attr_values"
}

i have setup it, but it not working
Steven Shaw
@steshaw
Hi, I've been consulting the docs at gorm.io. e.g. https://gorm.io/docs/advanced_query.html but I've realised that my project is using Gorm v1. Am I looking at the right docs?
Steven Shaw
@steshaw
Ah, seems I should have been looking at https://v1.gorm.io/. What a shame :(
Tal Tchernihovski
@taltcher
Hi - what is the best way to create an enum type with Gorm? is there a way to do it without manually creating the ENUM in the DB first?
Jared Green
@jaredgreener

I am quite confused by the "Has One" Association. It seems like the documentation is requiring fields in BOTH models (the owner and the child)-- which seems wrong. How would I structure the following models where multiple tables "Has One" record in the "entities" table:

type CreditType struct { // has one entity (Municipality)
gorm.Model
Name string json:"name"
Municipality Entity json:"municipality" // references a record in the "entities" table
}

type Transaction struct { // 2x has one entity (Buyer & Seller)
gorm.Model
Price decimal.Decimal json:"price"
Buyer Entity json:"buyer" // entities table record
Seller Entity json:"seller" // entities table record
}

type Entity struct { // entities table
gorm.Model
Name string json:"name"
}

1 reply
Gilson Araujo
@gilaraujo
Hello guys, I might be missing something, but I couldn't find anything about the SQL command UNION in gorm docs. Is it really not implemented yet? (I wanted to avoid using Raw query, if possible). Thanks in advance!
Thibault Vigouroux
@TeaBough
@jaredgreener that seems good to me, your Entity struct is not referencing CreditType nor Transaction
Asterisk
@Asteriskdev_gitlab
@jaredgreener :
Screenshot from 2021-09-25 13-00-06.png
gudjonvi
@gudjonvi

Hi all, I am trying to execute a simple where clause with an "in" statement
but I get a database error when I execute it:

def := db.Where("FIELDNAME IN ?", []string{"AmbientHumidity", "Pitch"}).Find(&fieldDefinitions)

The generated sql statment is:
SELECT * FROM "DATAFIELDDEFINITIONS" WHERE FIELDNAME IN (('AmbientHumidity','Pitch'))

The problem seems to be the double parenthesis, I'm using the sqlserver driver. Am I doing something wrong?

8 replies
Fredrik Holmqvist
@Holmqvist1990
Is there a way to add ORDER BY to a preload? Currently the preloaded items are sorted by id, whereas I want them to be sorted by a different order.
Jack Ma
@tieing
BUG is being created every day
great
tiendc
@tiendc

Hi, I have 2 tests as below:

Test A:
db = db.Where("name = 1").Where(db.Where("code = 2").Or("code = 3"))

Test B:
db = db.Where("name = 1")
db = db.Where(db.Where("code = 2").Or("code = 3"))

I expect the both tests will generate the same SQL "name = 1 AND (code = 2 OR code = 3)", but the 2nd doesn't.
It generates (name = 1 AND code = 2 OR code = 3 AND (name = 1 AND code = 2 OR code = 3)).

Is this proper behavior of GORM?

Marlon Wiprud
@marlon-wiprud
@Holmqvist1990 pretty sure you can add a callback to preload to perform your own modifications like ORDER BY
Im trying to switch the datatype of a gorm model struct from *uint64 => decimal.Decimal - the decimal package is from shopspring. However, when trying to create this model I get "cannot convert string to uint64"
any feedback is much appreciated!
Harry
@HarryChopra
Hi, A quick question. What are the methods available for updating only a few columns for a given row? For example:
// Retrieve a record from the table
user := &User{}
DB.Where("id = ?", 1).First(user)

// Changing a few values:
user.Name = "Harry"
user.Age = 30
user.Phone = 123456

// Update the row and allow only Name and Age columns to change:
<???> DB.Model(user).ONLY_UPDATE_COLUMNS(Name, Age) <???>
Elbek Kamoliddinov
@elbek
I have composite primary keys id and version. When I try to save the object it inserts into second column of composite key instead of letting db select the value. What might be wrong
Elbek Kamoliddinov
@elbek
it basically generates an insert query where version is part of the insert statement. INSERT INTO "attachments" ("version", ... But version is part of composite key and how can I dictate gorm not to insert value in version column
Edward Park
@parkedwards

possibly a dumb question - I wanted to see if folks had any advice for using db.AutoMigrate(struct) + adding a new column on a table that has a good amount of data (1-2MM rows). The new column wouldn’t be indexed

we’re using v1 gorm atm - should we have any concerns with table locking?

Robert Henzel
@rhenzel_gitlab

Hello,
Is there any way to get an information how the schema based on models will look after migration to database but without migrating it to any database instead write it to for eg. to map[table][]fields.
I want to make a tool that tells the difference between schemas based on models. I have two models which comes from two different versions of repository, in second one has field MiddleName added :

type User struct {
        // Base
    Base

    // Email
    Email string `gorm:"unique" rql:"filter" fake:"{email}"`

    // Password
    Password string `fake:"{password}"`

    // First name
    FirstName string `rql:"filter" fake:"{customPrefixName}"`

    // Last name
    LastName string `rql:"filter" fake:"{lastname}"`
}

type User struct {
        // Base
    Base

    // Email
    Email string `gorm:"unique" rql:"filter" fake:"{email}"`

    // Password
    Password string `fake:"{password}"`

    // First name
    FirstName string `rql:"filter" fake:"{customPrefixName}"`

    // Last name
    LastName string `rql:"filter" fake:"{lastname}"`

        // Middle name
    MiddleName string `rql:"filter" fake:"{middlename}"`
}

I want to see how different this tables would look in database. This is a simple example, the models I'm working on are more complicated, containing relations, foreign keys, association tables etc.
Thanks for any help. Cheers

kairye
@kairye
hello,
How can I implement payment by order time split table?
Alvaro Piorno
@apiorno
Hello, i am using gorm with postgres for some simple queries, isolated tables (no fk). and after some queries i am getting some kind of mixes in conditions and of course getting errors of "field not in table". I am getting queries like this "SELECT * FROM "certifications" WHERE (user_id = '1234567890') AND (user_id = '1234567890') LIMIT 100" . In this case the conditions was repeated but the problem was a condition from a previous query mixed with actual. Did someone get the same or similar?
func GetCertificationsOfUser(userID string) (*[]models.Certification, error) {

    var err error
    certifications := []models.Certification{}
    err = DBClient.Debug().Model(&models.Certification{}).Limit(100).Where("user_id = ?", userID).Find(&certifications).Error
    if err != nil {
        return &[]models.Certification{}, err
    }
    return &certifications, err

}
func FindUserById(uid string, role int) (*models.User, error) {
    var err error
    user := models.User{}
    //err = DBClient.Debug().Model(models.User{}).Where("passport = ? and role = ?", uid, role).Take(&user).Error
    err = DBClient.Raw("SELECT * FROM users WHERE passport = ?", uid).Scan(&user).Error

    if err != nil {
        return nil, err
    }
    if gorm.IsRecordNotFoundError(err) {
        return nil, fmt.Errorf("User Not Found")
    }
    return &user, err
}
Kasper
@repsak_gitlab
I'm running into an annoying issue. I have a user account, fetched from the DB (so not a new record), change a few values, then execute a db tx in which I do tx.Save(account). However, this gives me Error 1062: Duplicate entry '1' for key 'PRIMARY'". Any advice for how to debug this?
1 reply
Tor
@tveimo

Hi, am unable to get a Preload to work with gorm. Not sure if what I'm doing is correct.

type Message struct {
    ID        uuid.UUID  `json:"id" gorm:"type:char(36);primary_key;"`
    ...
    UserID        uuid.UUID        `json:"userId"`
    User        users.User        `json:"user" gorm:"foreignKey:UserID;"`
}

type User struct {
    ID        uuid.UUID  `json:"id" gorm:"type:char(36);primary_key;"`
    ...
}

Now, I'm trying to load a message from the message table, and get the User populated in the result, but it always shows up as an uninitialised struct. Am wondering if either I'm using the wrong query, or that this will not work well with uuid keys? I see in the logs that the correct queries seems to happen (with sqlite)

[12:15:24] DEBUG callbacks.preload(117): SELECT * FROM `users` WHERE `users`.`id` = "a9510182-463b-4202-93e8-7f462c62d2c2" [42.459µs]
[12:15:24] DEBUG content.LoadChannelMessages(55): SELECT * FROM `messages` WHERE channel_id = "adea9d6e-0a7c-448b-a86e-2ea59fa82715"  [106µs]
[12:15:24] DEBUG content.GetChannels(144): found messages: 1

any ideas?

Using query
    err = server.DB.Debug().
        Preload("User").Find(&messages, "channel_id = ? ", channelID).Limit(max).Error
just wondering if the use of uuid throws in a spanner here, as the query is correct for the preload
Hoàng Bùi
@mynamebvh
hello
Saifullah shaheen
@shahriar350
hey, I have a table of USERS. i want all user by groups where ACTIVE is bool(0/1). how can I get user by ACTIVE group?
tritueviet
@tritueviet
hello, i have a question to force truncate table in golang gorm.
how can i force truncate with disable force key check in mysql?
Nikolas
@salokin:matrix.org
[m]
Hi I need to have some sql "bigint unsigned" in my model. I would appreciate any hints. Could not find something in the docs... Thank you!
8 replies
William Ye
@wenbingy
nice to be here, really excited to see gorm tech issues being widely discussed
any articles/patterns/open source code for gorm multi-tenant support especially for postgres ?
i was thinking about using dbresolver but it seemed it handles different problems instead of multi-tenant
we plans to support multi-tenant by using different postgres schemas which can be switched by setting search path, but doesn't get a good pattern how to handle it
Nikolas
@salokin:matrix.org
[m]
When trying to save a model with a big.Int field, I get 'sql: converting argument $3 type: unsupported type big.Int, a struct' - seems to me gorm cannot handle the field value
Ben Hall
@BenHall-1

Really weird thing (for me at least)

I have two models

  • Organisations
  • Users

I want to assign an OrganisationMod (dictated by Moderators []*User `json:"Moderators" gorm:"many2many:organisation_moderators;" on the Organisation object) however when I use db.DB.Model(&organisation).Association("Moderators").Append(&newModerator); where &organisation is a valid object and newModerator is an existing user - it attempts to create another user and I'm not sure why

Jason McNeil
@sixcolors
using .Find(&Thing, id) always returns an empty Thing even if it doesn't exist. Is this intentional?
Jenda Mudron
@jenmud

how does one update Zero value fields, eg pseudocode:

type Company struct {
    gorm.Model
    Employees []*Employee
}

type Employee struct {
    gorm.Model
    CompanyID uint
    Name string
}

I would like to update the company with zero employees. Seems that when using zero values gorm ignores it even if I do something like this (pseudocode below)

company := &Company{ID: 1, Employees: []*Employee{}}
db.Model(&Company{}).Select("*").Update(company)
Jason McNeil
@sixcolors

using .Find(&Thing, id) always returns an empty Thing even if it doesn't exist. Is this intentional?

ie .Error is nill even if id does not exsist.