Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
Sean Abbott
@sean-abbott

Ok, more newbyness if anyone can help:

type User Struct {
     gorm.Model
}

type Follow struct {
    gorm.Model
    // obviously, these are foreign keys. And I don't understand gorm's assocations documentation
    FollowedUser User
    FollowerUser User
}

if err := db.FirstOrCreate(&f, Follow{FollowedUser: followed, FollowerUser: follower}).Error

Yields sql: converting argument $1 type: unsupported type main.User, a struct

So I have no idea how to actually create a Follow with this setup.

And if anyone could help me try to understand the assocations and a good way to structure this, I would sure appreciate it
Sean Abbott
@sean-abbott

I can get it to work by doing

type Follow struct {
    gorm.Model
    FollowedUserId uint
    FollowerUserId uint
}
    if db.Where("followed_user_id = ? AND follower_user_id = ?", fr.FollowedUserId, fr.FollowerUserId).First(&f).RecordNotFound() {
        f = Follow{FollowedUserId: fr.FollowedUserId, FollowerUserId: fr.FollowerUserId}
        db.Create(&f)
    }

Instead, but I'm sure I'm missing out on good things this way

Neutron Stein
@neutronstein
Hi. Is returning fields after update or insert supported? Thanks
Neutron Stein
@neutronstein
I found a workaround using Raw and Scan. Eg: db.Raw("UPDATE players SET score = score + ? WHERE id = ? RETURNING *", 10, 1).Scan(&player)
Hamza Ali
@Hamzantal
This message was deleted

What should I be doing differently to get each row of this sql statement result into a struct?

rows, _ := db.Where("status = ?", 0).Find(&common.Shipment{}).Rows()
for rows.Next() {
    shipment := common.Shipment{}
    rows.Scan(&shipment)

    bytes, _ := json.Marshal(shipment)
    println(string(bytes))
}

edit: solved :)

Zane Witherspoon
@ZaneWithSpoon
Hi there community! I'm trying to integrate gorm migrations but for some reason db.AutoMigrate(&Consumer{}) is only creating the table but not creating any columns. Any ideas?
And here is my struct:
type Consumer struct { email string `gorm:"type:varchar(200);unique_index"` auth string `gorm:"type:varchar(100)"` dashId string `gorm:"type:varchar(25)"` user_data []byte `gorm:"type:jsonb"` testMigration string }
Or does anyone have an active link to the slack channel if that's a more appropriate place to ask?
Zane Witherspoon
@ZaneWithSpoon
Answer was struct variables needed to be Capitalized
andreGarvin
@andreGarvin
Hello, I was wondering can you do method chaining like this in gorm and will it execute as expected.
query := classroom.db.Table("classrooms").Select("users.full_name, users.photo_url, users.email, classrooms.color, classrooms.name")
    query.Where("archived = false")
    query.Joins("classroom_members ON ('classroom_members'.'classroom_id' = 'classrooms'.'id')")
    query.Joins("users ON (users.id = classrooms.creator)")
    query.Where("'classroom_members'.'user_id' = $1 AND 'classroom_members'.'removed' = false AND 'classrooms'.'archived' = false", userID)
if anyone needs more context just @ me, sorry it is is very vague
Jacob Henner
@JacobHenner_gitlab
I'm getting the following error: sql: converting argument $2 type: unsupported type []*main.Coordinator, a slice of ptr when I try to create an object with one field ( a many2many) set to the above type - shouldn't it recognize it automatically, or does many2many require a different syntax than the other associations?
type Coordinator struct {
    gorm.Model
    Email           string           `gorm:"primary_key;not null"`
    EventCategories []*EventCategory `gorm:"many2many:event_category_coordinators;"`
}
type EventCategory struct {
    gorm.Model                             
    Category        string                  `gorm:"primary_key;not null"`
    Coordinators    []*Coordinator          `gorm:"many2many:event_category_coordinators;not null;"`
Lorenzo Avallone
@reloonfire

Hello, i'm getting the following error: pq: missing FROM-clause entry for table "item" when i try to get an entity from the DB that have a polymorphic associations with a struct.

type Crafted struct {
    gorm.Model
    Item     Item `gorm:"polymorphic:Item;"`
    RecipeID uint
    Recipe   Recipe
}
type Item struct {
    gorm.Model
    Name     string `gorm:"unique;not null"`
    RarityID uint
    Rarity   Rarity
    ItemID   uint
    ItemType string
}

The query is DBConnection.Preload("Item").Preload("Item.Rarity").Preload("Recipe").Where("Item.name = ?", name).First(&craft)

matrixbot
@matrixbot
Paul have you logged the sql?
Lorenzo Avallone
@reloonfire
image.png
yes, but i changed the query a bit.
DBConnection.Preload("Item", "Name = ?", name).Preload("Item.Rarity").Preload("Recipe").Find(&craft)
Lorenzo Avallone
@reloonfire
Why GORM in the preload use the 14 (rows founded) as item_id, i have 14 elements, so i presume that the item_id need to be IN (1,2,3,4,5,6,7,8,9,10,11,12,13,14)
@matrixbot
Lorenzo Avallone
@reloonfire
image.png
Without the where conditions works fine, but i need to apply a filter
ChanForPres
@ChanForPres
hi slack invite expired
please repost
Brent Hamilton
@distrill
I'm trying to use hooks to do something whenever a record is updated, but hooks apparently don't work for batch updates. Is it considered acceptable behavior to just ignore this? Is there any way I can hook into batch updates? I don't think I can rely on the rest of the team just agreeing to not use batch updates anywhere in the code base.
Jacob E. Shore
@DewofyourYouth
when I query my sqlite db I get &{{{0 0} 0 0 0 0} 0xcb0850 <nil> 1 0xc0000b4480 false 0 {0xc0000f1db0} 0xc000246f20 {{0 0} {{map[gorm:order_by_primary_key:0xc000011618] false}} map[] 0} 0xc00008aea0 <nil> 0xc00024c880 false <nil>}
what does it mean?
matrixbot
@matrixbot
Paul is that the result?
Paul print using fmt.Printf("%+v", ...) or fmt.Printf("%# v", pretty.Formatter(...))
Jacob E. Shore
@DewofyourYouth
So I'm not Paul, but I tried that and got this &gorm.DB{RWMutex:sync.RWMutex{w:sync.Mutex{state:0, sema:0x0}, writerSem:0x0, readerSem:0x0, readerCount:0, readerWait:0}, Value:(*cocktails.Cocktail)(0xc000238630), Error:error(nil), RowsAffected:1, db:(*sql.DB)(0xc0000b4480), blockGlobalUpdate:false, logMode:0, logger:gorm.Logger{LogWriter:(*log.Logger)(0xc0000f1db0)}, search:(*gorm.search)(0xc00023cb00), values:sync.Map{mu:sync.Mutex{state:0, sema:0x0}, read:atomic.Value{v:sync.readOnly{m:map[interface {}]*sync.entry{"gorm:order_by_primary_key":(*sync.entry)(0xc000011540)}, amended:false}}, dirty:map[interface {}]*sync.entry(nil), misses:0}, parent:(*gorm.DB)(0xc000088dd0), callbacks:(*gorm.Callback)(nil), dialect:(*gorm.sqlite3)(0xc00023e1e0), singularTable:false, nowFuncOverride:(func() time.Time)(nil)}
matrixbot
@matrixbot
Paul I'm Paul, the bridge sends all matrix messages through a single bot
Paul so you got a gorm.DB struct
Jacob E. Shore
@DewofyourYouth
Oh, go it
thanks
matrixbot
@matrixbot
Paul what was the function call you used to get it?
Jacob E. Shore
@DewofyourYouth
db.First
matrixbot
@matrixbot
Paul you should pass db.First a pointer to the result
Paul and not look at the return value
Jacob E. Shore
@DewofyourYouth
this is what I did
first := db.First(&cktl, 1) fmt.Printf("%#v\n", *first)
matrixbot
@matrixbot
Paul fmt.Printf("%v\n", cktl)
Paul first is not the result
Paul ctkl is the result
Paul look at the quick start guide
Jacob E. Shore
@DewofyourYouth
ok, will look again, thanks
awesome, that worked
matrixbot
@matrixbot
Paul great
Dr. Doofenshmirtz
@noelukwa_twitter
type User struct {
    ID        int `gorm:"AUTO_INCREMENT,primary_key"`
    Name      string
    Age       string
    Followers []User
    Following []User
}
But it doesnt show in my db
Please how do i model a has many relationship.. i've tried this but it doesnt work