Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
  • Jun 24 19:29
    endophage edited #4478
  • Jun 24 18:47
    endophage edited #4478
  • Jun 24 18:20
    endophage edited #4478
  • Jun 24 18:15
    endophage edited #344
  • Jun 24 18:14
    github-actions[bot] labeled #4478
  • Jun 24 18:14
    endophage assigned #4478
  • Jun 24 18:14
    endophage opened #4478
  • Jun 24 18:12
    endophage opened #344
  • Jun 24 16:15
    xushiwang commented #4403
  • Jun 24 14:12
    github-actions[bot] unlabeled #4477
  • Jun 24 14:12
    github-actions[bot] labeled #4477
  • Jun 24 14:12
    20Aditya edited #4477
  • Jun 24 14:03
    github-actions[bot] labeled #4477
  • Jun 24 14:03
    20Aditya opened #4477
  • Jun 24 13:00
    github-actions[bot] closed #4471
  • Jun 24 07:41
    github-actions[bot] closed #4468
  • Jun 24 03:45
    github-actions[bot] closed #4467
  • Jun 24 02:24
    bingoohuang edited #4476
  • Jun 24 02:24
    bingoohuang opened #4476
  • Jun 24 02:09
    github-actions[bot] unlabeled #3832
Manish Kumar
@manish.kumar5_gitlab
Anyone have idea how to do it?
Tobias
@teletobbie

Hello,

I am implementing some delete functionality using GORM. My idea is to cascade delete where when the parent row is deleted, the childern are deleted aswell. I have tried the delete with select. But it only deletes the parent record.

func DeleteProject(db *gorm.DB, id uint) (Project, error) {
    var project Project
    if err := db.Select(clause.Associations).Delete(&project, id).Error; err != nil {
        return Project{}, err
    }
    return project, nil
}

I have the following model:

type Project struct {
    ID           uint           `gorm:"primary_key" json:"id"`
    CreatedAt    time.Time      `json:"created_at"`
    UpdatedAt    time.Time      `json:"updated_at"`
    DeletedAt    gorm.DeletedAt `gorm:"index" json:"deleted_at"`
    TicketNumber string         `gorm:"size:6;unique;not null" json:"ticketnumber"`
    Name         string         `json:"name"`
    MailingList  string         `json:"mailinglist"`
    Environment  string         `gorm:"not null" json:"environment"`
    UserID       uint           `gorm:"index" json:"user_id"`
    Diagrams     []Diagram      `json:"diagrams"`
}

type Diagram struct {
    ID        uint           `gorm:"primary_key" json:"id"`
    CreatedAt time.Time      `json:"created_at"`
    UpdatedAt time.Time      `json:"updated_at"`
    DeletedAt gorm.DeletedAt `gorm:"index" json:"deleted_at"`
    Data      string         `json:"data"`
    ProjectID uint           `gorm:"index" json:"project_id"`
    Instances []Instance     `json:"instances"`
}

type Instance struct {
    ID        uint           `gorm:"primary_key" json:"id"`
    CreatedAt time.Time      `json:"created_at"`
    UpdatedAt time.Time      `json:"updated_at"`
    DeletedAt gorm.DeletedAt `gorm:"index" json:"deleted_at"`
    Key       uint           `json:"key"`
    DiagramID uint           `gorm:"index" json:"diagram_id"`
}

Where a project can have multiple diagrams and a diagram can have multiple instances. But when I am running the DeleteProject function it is only deleting the Project and not the associated diagrams and instances.

How can I delete a project and it's associated diagrams and instances in this case?

Thank you!
Lucas Pinto
@luckspt

Hi! I'm having a bit of trouble selecting multiple rows.
I have defined User as

type User struct {
    ID        string `gorm:"primaryKey"`
    Name      string
    IsAdmin   bool `gorm:"default:false"`
    CreatedAt time.Time
    UpdatedAt time.Time
    DeletedAt gorm.DeletedAt
}

and am trying to get all users with

var users []models.User
result := db.GetDB().Find(&users)

but keep getting runtime error: invalid memory address or nil pointer dereferenceon the last line

jonah
@jonah:matrix.psytux.com
[m]
Try something like db.Model(&models.User{}).Find(&users)
Lucas Pinto
@luckspt
Thanks @jonah:matrix.psytux.com but I forgot to update my message. I have fixed it - db.GetDB() was nil/undefined (I'm just starting with go)
ConaGo
@ConaGo

Hi there! I need some help with a simple query.

These are my data models(simplified)

type Conference struct {
    gorm.Model                        `json:"-"`
    Name      string             
    Tags      []Tag                 `gorm:"many2many:conference_tags;"`

}

type Tag struct {
    gorm.Model                        `json:"-"`
    TagName       string
    Conferences []Conference        `gorm:"many2many:conference_tags;"`
}

My Goal is to query so that:
given a list of tags
a list of conferences that are connected to the given tags is returned

My attempts were to preload the tags into the conference table
starting with this query i was not able to access the tagnames and filter by those

db.Preload("Tags").Find(&conferences)
db.Preload("Tags").Where("tag_name IN ?", []string{"javascript", "css", "devops"}).Order("start_date ASC").Find(&conferences) //fails

second query outupts cannot find table named tag_name
(this example is just to illustrate my problem.. Ive tried multiple things and failed)

second attempt was to start with the tag table

db.Where("tag_name IN ?", []string{"javascript", "css", "devops"}).Preload("Conferences").Group("tag_name").Find(&tags)

While this neatly groups conferences to tags it is also a one-to-many association and not how i need my data

my desired result looks like this

Result=[
    {
        Name:CSS Day,
        Tags:
        [
            {
                TagName:css
            },
            {
                TagName:html
            }
        ]
    },
    {
        Name:Devops Day,
        Tags: [
            {
                TagName:devops
            }
        ]
    }
]
.....

Any help is greatly appreciated :)

Sivakumar
@kumarsiva07
DB.model is not resetting the table name after find. I tried to find from table1 and want update table2 using same db object. But update query formed with table1 instead of table2
doppl-neal
@doppl-neal
Can you post some code?
Lucas Pinto
@luckspt
[postgres] Hi! I'm having an issue with a query. My query is the following: res := db.GetDB().Model(&db.User{}).First(&user, "id = ?", userID) and then resolves to SELECT * FROM "users" WHERE id = 'tHi9KeXYpMhqyKSUUpmkBpK0Z9F2' AND "users"."deleted_at" IS NULL ORDER BY "users"."id" LIMIT 1.
However, it says it found 0 rows when there is one. If I run the same query in pgadmin, I get a result.
Lucas Pinto
@luckspt
nevermind. user already had data and making a new var for the query fixed it
Evert Arends
@Evert-Arends
Hello everyone. Anyone knows if the documentation of this library is still relevant?
I have hit my toes many, many times. We're trying to create a rest API with go and gorm, but damn this documentation doesn't seem to work for me
I'm talking about gorm.io/gorm v1.21.10
Cascade does not seem to work (not a soft delete)
type Category struct {
    gorm.Model  `json:"gorm_model"`
    Name        string  `json:"name"`
    Description string  `json:"description"`
    ParentID    int     `json:"parent_id"`
    Parent      *Category `gorm:"foreignKey:ParentID;constraint:OnUpdate:CASCADE,OnDelete:CASCADE;"`
}
Mark Gascoyne
@mgazza
Good morning guys. having a bit of trouble getting gorm to produce the correct model. So we need to model a polymorphic structure. Where the main struct has a slice of interface. This interface has multiple implementations. each of these types lives in a sparse columns table. any help?
Mark Gascoyne
@mgazza
Gorm complains when i switch from the "base struct" to an interface type with "unsupported data type"
package model

type Post struct {
    Id       string `gorm:"primaryKey"`
    Text     string
    Title    string
    SubTitle string
}

type Fragment interface {
    ID() string
    Name() string
}

type fragment struct {
    id      string `gorm:"primaryKey"`
    name    string
    Block   Block
    BlockID string
    Type string
}

func (f fragment) ID() string {
    return f.id
}

func (f fragment) Name() string {
    return f.name
}

type TextFragment struct {
    fragment
    Content string
}

type ImageFragment struct {
    fragment
    URI string
}

type VideoFragment struct {
    fragment
    URI string
}

type ProofStepFragment struct {
    fragment
    ReportUri string
    Content   string
    Buttons   int
}

type Block struct {
    Id       string `gorm:"primaryKey"`
    Name     string
    Fragments []Fragment `gorm:"polymorphic:;"`
    StageID  string `gorm:"column:stage_id"`
    Stage    Stage
}

type Stage struct {
    Id       string `gorm:"primaryKey"`
    Name     string
    Blocks   []Block `gorm:"foreignkey:stage_id"`
    CourseID string  `gorm:"column:course_id"`
    Course   Course
}

type Course struct {
    Id     string `gorm:"primaryKey"`
    Name   string
    Stages []Stage `gorm:"foreignkey:course_id"`
}

type Company struct {
    Id     string `gorm:"primaryKey"`
    Name   string
    Course []Course `gorm:"many2many:company_courses;"`
}
package model

type Post struct {
    Id       string `gorm:"primaryKey"`
    Text     string
    Title    string
    SubTitle string
}
/*
type Fragment interface {
    ID() string
    Name() string
}
*/
type Fragment struct {
    id      string `gorm:"primaryKey"`
    name    string
    Block   Block
    BlockID string
    Type string
}

func (f Fragment) ID() string {
    return f.id
}

func (f Fragment) Name() string {
    return f.name
}

type TextFragment struct {
    Fragment
    Content string
}

type ImageFragment struct {
    Fragment
    URI string
}

type VideoFragment struct {
    Fragment
    URI string
}

type ProofStepFragment struct {
    Fragment
    ReportUri string
    Content   string
    Buttons   int
}

type Block struct {
    Id       string `gorm:"primaryKey"`
    Name     string
    Fragments []Fragment `gorm:"polymorphic:;"`
    StageID  string `gorm:"column:stage_id"`
    Stage    Stage
}

type Stage struct {
    Id       string `gorm:"primaryKey"`
    Name     string
    Blocks   []Block `gorm:"foreignkey:stage_id"`
    CourseID string  `gorm:"column:course_id"`
    Course   Course
}

type Course struct {
    Id     string `gorm:"primaryKey"`
    Name   string
    Stages []Stage `gorm:"foreignkey:course_id"`
}

type Company struct {
    Id     string `gorm:"primaryKey"`
    Name   string
    Course []Course `gorm:"many2many:company_courses;"`
}
sort of works but obviously can't work as Fragment is nolonger an interface type
image.png
obviously the sparse columns needs work too
Mark Gascoyne
@mgazza
but yea i don't see how polymorphism can work in go if collections of interfaces are not supported
image.png
Mark Gascoyne
@mgazza
this is what i want to produce
image.png
Mark Gascoyne
@mgazza
so gave up getting polymorism working with this. next on the board.... select users.companies.courses ... ah yea this doesnt work either. /puts gorm in the bin
Norman
@normangoh
Hi guys, I am wondering how do I use schema with joins in Gorm. Anyone knows how?
Kumar SIVA
@kumarsiva07_gitlab
This message was deleted
How to query same table in callback?     

db.Callback().Update().Before("gorm:update").Register("obz:old_object", loadOldObject)

func loadOldObject(db *gorm.DB) {
    fmt.Println("******************* loadOldObject ************************")
    orgID, orgExists := db.Get("org_id")
    field, ok := db.FieldByName("OldObject")
    if field != nil && orgExists {
        object := db.IndirectValue()
        objectType := reflect.TypeOf(object)       // this type of this variable is reflect.Type
        objectPointer := reflect.New(objectType)   // this type of this variable is reflect.Value.
        objectValue := objectPointer.Elem().Addr() // this type of this variable is reflect.Value.
        objectInterface := objectValue.Interface()
        field.Set(objectInterface)
        db := db.DB().Table(db.TableName())
        if orgID != nil {
            db.Where(db.Statement.Table+".org_id = ?", orgID)
        }
        db.Where(db.PrimaryKey()+" = ?", db.PrimaryKeyValue()).First(field.Field.Interface())
    }
}

I did this in form V1. Please help me to achieve in v2
Matías Chapresto
@matiaschapresto_gitlab
Hey guys, do you kno when will GORM have orphan removal?
Evert Arends
@Evert-Arends
I'm pretty sure Gorm doesn't work anymore
The documentation seems to be incorrect
3 replies
And the things that are marked don't work. Anyone has a comparable project so I can remove gorm from my sourcecode?
Alessandro Sechi
@AlessandroSechi

Hello. Having some strange issues with Gorm.

type VM struct {
    ID                 string
    TypeId             string          `gorm:"type:string;size:191;index"`
    Type               VMType          `gorm:"references:TypeId"`
}

type VMType struct {
    ID                 string `gorm:"primaryKey;index"`
    Name               string `gorm:"primaryKey;index"`
}

gives me this error:

define a valid foreign key for relations or implement the Valuer/Scanner interface

Alessandro Sechi
@AlessandroSechi
Found the solution, kinda insane. The problem was in another struct, in which a FK was defined on a pointer field, but for apparently no reason GORM said in was in VM struct. Cool.
Kumar SIVA
@kumarsiva07_gitlab
@AlessandroSechi Please help me to get the changed set after the update.
eyJhb
@eyjhb:eyjhb.dk
[m]
And I get to play with reflect.. which is a nice skillset
But it is a great project none the less.. the documentation for anyone not in the space is just very very lacking.
Alessandro Sechi
@AlessandroSechi
@kumarsiva07_gitlab unfortunately I'm not able to help you
Zein Fahrozi
@mozarik
Hi i have this code i dont know is this correct or not. I dont know why when im doing this MerchantProduct doesnt make MerchProd.Product_id as FK pointing to Product.ID
type MerchantProduct struct {
    Product_id uint `json:"product_id"`
    MerchantID uint `json:"merchant_id"`
    // Product    []Product `gorm:"foreignkey:ID ;association_foreignkey:Product_id" json:"product"`
}

type Product struct {
    gorm.Model
    Name            string          `json:"name"`
    Sku             uint            `json:"sku"`
    Image           string          `json:"image"`
    MerchantProduct MerchantProduct `gorm:"foreignkey:Product_id;association_foreignkey:ID"`
}
image.png
Daniel Marchi Silva
@dmarchi775

Hi guys!
Question, theres a way that i can do not insert duplicate itens? my table has an id and name fields, only the id is my PK (auto increment) and i dont want to insert duplicate names

I tried something like this, but not work, it keeps inserting records if the fields initiative_name already exists in the database

db.Table(constant.TableNameInitiativesTracking).Clauses(clause.OnConflict{
            Columns:   []clause.Column{{Name: "initiative_name"}},
            DoNothing: true,
        }).Create(&initiatives).Error

my model

type InitiativeTracking struct {

    Id             int    `db:"id" json:"id,omitempty"`

    InitiativeName string `db:"initiative_name" json:"name" binding:"required"`

}

Tks

353946275
@353946275
yes, i think it is very good
Eduardo Mior
@eduardo-mior
Is it possible to get the SQL generated by gorm somehow without using DryRun ?
2 replies
RebootCode
@rebootcode
how to make createdAt and updatedAt - auto update without specifying every time in create and update
?
instead of writing CreatedAt := time.Now() I want it to be automated that table auto update time
Satya kumar Itekela
@itesatti_twitter

I am trying to add array data type using gorm
type Token struct {
Base
Tags pq.StringArray json:"tags"
}
using
t.DB.Model(&database.Token{}).Where("address = ?", address).Update(&database.Token{
Tags: ["1","2"],
})

But, I am unable to append a new tag to the data. It is getting replaced..
Any idea??