douzhongju8780 2016-12-21 07:41
浏览 76

如何使用json将自动增量添加到Go结构

EDITED 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条回答 默认 最新

  • doudaotui4297 2016-12-21 09:28
    关注

    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")
    }
    

    }

    评论

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题