文章表数据语句
CREATE TABLE `posts` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`category_id` int(11) unsigned NOT NULL DEFAULT '0',
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`deleted_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE,
UNIQUE KEY `post-test` (`text`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8mb4 COMMENT='文章';
分类表数据语句
CREATE TABLE `old_liu_categories` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`deleted_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COMMENT='分类';
文章的model
type Posts struct {
ID uint64 `gorm:"column:id;primaryKey;autoIncrement;" json:"id"`
CategoryId int `json:"category_id"`
Categories Categories `json:"category" gorm:"ForeignKey:CategoryId"`
CreatedAt time.Time `gorm:"column:created_at;index;" json:"created_at,omitempty"`
UpdatedAt time.Time `gorm:"column:updated_at;index;" json:"updated_at,omitempty"`
}
分类的model
type Categories struct {
ID uint64 `gorm:"column:id;primaryKey;autoIncrement;" json:"id"`
CreatedAt time.Time `gorm:"column:created_at;index;" json:"created_at,omitempty"`
UpdatedAt time.Time `gorm:"column:updated_at;index;" json:"updated_at,omitempty"`
}
当查询文章列表时候要看到所属的分类
func (p *Posts) List(page, pageSize int, where map[string]interface{}) (error, int64, interface{}) {
query := database.DB.Model(Posts{}).Preload("Categories")
var total int64
var results []Posts
if where["title"] != "" {
query.Where("title=?", where["title"])
}
if where["text"] != "" {
query.Where("text=?", where["text"])
}
query.Count(&total)
return query.Offset((page - 1) * pageSize).
Limit(pageSize).
Find(&results).Error, total, results
}