iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 27
0
Modern Web

BeeGo系列 第 27

blog (1) - 規劃與 model

剩下四天,讓我們開始寫簡單的 blog 吧。

我們延續之前的程式,Member 這個 model 就當作文章的作者,基本上,只增加這幾個部份

  • 文章 (Post) 的資料定義
  • 前台的呈現
    • 首頁,呈現最新的 10 篇文章,需要有分頁
    • 單篇文章
  • 後台文章的管理,需要有 List, Create, Update, Delete

先來定義文章 (Post) 這個 model,我們需要有這些欄位

  • MemberId
  • Title
  • Content
  • Posted_at
  • Modified_at

MemberId 是用來跟之前建立的 Member 關聯用的,Title 跟 Content 則是文章的標題跟內容,Posted_at 跟 Modified_at 則是文章的張貼時間跟變更時間。

先使用 bee generate model 來建立

bee generate model Post -fields="title:string,content:string,posted_at:datetime,modified_at:datetime"

再建立 migration

bee generate migration post -fields="memberId:int,title:string,content:string,posted_at:datetime,modified_at:datetime" -driver="mysql"

然後開啟 models/post.go 來增加 Foreign key:Member

// models/post.go
type Post struct {
        Id         int64     `orm:"auto"`
        Member     *Member   `orm:"rel(fk)"`
        Title      string    `orm:"size(128)"`
        Content    string    `orm:"size(8192)"`
        PostedAt   time.Time `orm:"type(datetime)"`
        ModifiedAt time.Time `orm:"type(datetime)"`
}

再來改 database/migrations/ 下的 xxxx_post.go,這是產出的 migration,一樣是修改 DDL 的資料型態,並加上 Foreign Key 的定義。

// Run the migrations
func (m *Post_20191001_071922) Up() {
        // use m.SQL("CREATE TABLE ...") to make schema update
        m.SQL("CREATE TABLE post(`id` int(11) NOT NULL AUTO_INCREMENT,`member_id` int(11) DEFAULT NULL,`title` varchar(128) NOT NULL,`content` text NULL,`posted_at` datetime NOT NULL,`modified_at` datetime NOT NULL,PRIMARY KEY (`id`),FOREIGN KEY(member_id) REFERENCES member(id))")
}

最後再執行 bee migrate 就完成資料庫的變更了。


上一篇
佈署
下一篇
blog (2) - 前台呈現
系列文
BeeGo30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言