我在 GoLang 中定義了這些型別:
type Comment struct {
Id int
User string
Email string
Date string
Comment string
}
type Post struct {
Id int
Special bool
Title string
Date string
Content string
Image string
Comments []Comment
}
我需要知道如何修改此代碼:
OpenDB()
rows, _ := cn.Query(`SELECT id, date, title, special, content, image
FROM posts ORDER BY date DESC LIMIT $1
OFFSET $2`, fmt.Sprint(limit), fmt.Sprint(offset))
posts := []Post{}
for rows.Next() {
post := Post{}
e := rows.Scan(&post.Id, &post.Date, &post.Title,
&post.Special, &post.Content, &post.Image)
if e != nil {
panic(e)
}
posts = append(posts, post)
}
允許閱讀評論。而且,我如何修改:
OpenDB()
_, e = cn.Exec(`INSERT INTO
posts(date, title, special, content, image)
VALUES ($1, $2, $3, $4, $5)`, date, title, special, content, image)
if e != nil {
panic(e)
}
defer CloseDB()
允許寫入空的注釋陣列。
最后,如果有人告訴我如何將單個評論寫入現有帖子,我將不勝感激。
uj5u.com熱心網友回復:
這取決于您的資料庫架構。
如果Comment有自己的表,則必須遍歷 a 中的所有注釋,Post并在插入Post. cn.Exec應該回傳一個Result,可用于獲取最后插入的 ID,如:
result, err := cn.Exec(...)
if err != nil {
panic(err)
}
id, err := result.LastInsertId()
if err != nil {
panic(err)
}
您現在可以使用帖子的 ID 作為外鍵。
如果您使用JSON列來存盤您的評論,您應該定義一個自定義型別作為別名[]Comment,并使該型別實作sql.Scanner和driver.Valuer。
type Comment struct {
Id int
User string
Email string
Date string
Comment string
}
type Comments []Comment
// Make the Comments type implement the driver.Valuer interface. This method
// simply returns the JSON-encoded representation of the struct.
func (c Comments) Value() (driver.Value, error) {
return json.Marshal(c)
}
// Make the Comments type implement the sql.Scanner interface. This method
// simply decodes a JSON-encoded value into the struct fields.
func (c *Comments) Scan(value interface{}) error {
var b []byte
switch t := value.(type) {
case []byte:
b = t
case string:
b = string(t)
default:
return errors.New("unknown type")
}
return json.Unmarshal(b, &c)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/358296.html
標籤:PostgreSQL的 走
下一篇:忽略的YAML標簽
