These are chat archives for jinzhu/gorm

23rd
Mar 2016
Cristian Sima
@cristian-sima
Mar 23 2016 15:31
hi mates.
Any idea how to do this?
  1. check if a item is in the database (where)
  1. in case it is save all its fields (save)
  1. in case it is not to create it
I have tried to do with tx.Where(whereClause).Assign(&activity).FirstOrCreate(&activity) but it has a strange behaviour
Cristian Sima
@cristian-sima
Mar 23 2016 15:46
I ended using this:
dbActivity := payroll.Activity{}

if company.Where(whereClause).First(&dbActivity).RecordNotFound() {
    // not found
    if err := tx.Create(&activity).Error; err != nil {
        tx.Rollback()
        return err
    }
} else {
    activity.ID = dbActivity.ID
    if err := tx.Save(&activity).Error; err != nil {
        tx.Rollback()
        return err
    }
}
Maybe it is a good idea to create a func UpdateOrInit which behaves like this
Thomas Boerger
@tboerger
Mar 23 2016 16:11
@cristian-sima that's how i do it
        db.Where(
            model.Forge{
                Name: number.ID,
            },
        ).Attrs(
            model.Forge{
                Minecraft: number.Minecraft,
            },
        ).FirstOrCreate(
            &record,
        )
model.Forge is one of my models and record is an instance of a model.Forge model