How to add auto increment to Go struct with json

6.5k views Asked by At

I want to override Id value field in GORM with since I am using json also to marchal and unmarshall.

package article

import "github.com/jinzhu/gorm"

type Article struct {
    gorm.Model
    Id          int    `json:"id"`
    Title       string `json:"title"`
    Description string `json:"description"`
    Content     string `json:"content"`
}

I wish to add gorm property like this

`gorm:"default:'galeone'"`

But it is not compiling

package article

import "github.com/jinzhu/gorm"

type Article struct {
    gorm.Model
    Id          uint    `json:"id" sql:"AUTO_INCREMENT" gorm:"primary_key"`
    Title       string `json:"title"`
    Description string `json:"description"`
    Content     string `json:"content"`
}

I am using Gorm from here [https://github.com/jinzhu/gorm][1]

I am getting

2016/12/21 15:17:48 DB Initialized successfully

(duplicate column name: id) 
[2016-12-21 15:17:48]  

(no such table: articles) 
[2016-12-21 15:17:48]  

This is how i am creating DB it is working fine just want auto increment on Article struct

package dbprovider

import (
    "github.com/jinzhu/gorm"
    _"github.com/jinzhu/gorm/dialects/sqlite"
    "rest/article"
    "log"
)

var db gorm.DB

var isInitialized bool

func InitDb() {
    isInitialized = false
    db, err := gorm.Open("sqlite3", "../../articles.db")

    if (db != nil && err == nil) {
        log.Print("Db Initialized")
        isInitialized = true
    } else {
        isInitialized = false
        defer db.Close()
        log.Panic("DB not initialized")
    }
}

func AddArticle(article *article.Article) {
    if (isInitialized) {
        db.Create(&article)
    }
}
1

There are 1 answers

0
King Jk On

First. According to Office Guideline gorm:"default:'galeone'" is your field default value

Refer : gormDefaultValue when you not give the value. so your ID field need to be change . because your default value is string but the field is int

Id    int    `json:"id" gorm:"default:1"`

and on func InitDb. you redefinition a variable db.Will occur error when you compiler or run go program. you need change two line 1. var db gorm.DB -> var db *gorm.DB 2. func InitDb

func InitDb() {
isInitialized = false
//Change below code 
var err interface{}
db, err = gorm.Open("sqlite3", "../../articles.db")

if (db != nil && err == nil) {
    log.Print("Db Initialized")
    isInitialized = true
} else {
    isInitialized = false
    defer db.Close()
    log.Panic("DB not initialized")
}

}