原来的案例是 商城系统的收藏夹的关系,收藏夹里面需要有收藏用户,产品,产品用有人的信息,因此下面的结构如此体现,这样子设计非常巧妙,使用了belong to
1 2 3 4 5 6 7 8 9
type Favorite struct { gorm.Model User User `gorm:"ForeignKey:UserID"` UserID uint`gorm:"not null"` Product Product `gorm:"ForeignKey:ProductID"` ProductID uint`gorm:"not null"` Boss User `gorm:"ForeignKey:BossID"` BossID uint`gorm:"not null"` }
下面的分别是用户和产品的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
type Product struct { gorm.Model Name string`gorm:"size:255;index"` CategoryID uint`gorm:"not null"` Title string Info string`gorm:"size:1000"` ImgPath string Price string DiscountPrice string OnSale bool`gorm:"default:false"` Num int BossID uint BossName string BossAvatar string }
1 2 3 4 5 6 7 8 9 10 11
type User struct { gorm.Model UserName string`gorm:"unique"` Email string PasswordDigest string NickName string Status string Avatar string`gorm:"size:1000"` Money string Relations []User `gorm:"many2many:relation;"` }
func(dao *FavoritesDao) ListFavoriteByUserId(uId uint, pageSize, pageNum int) (r []*types.FavoriteListResp, total int64, err error) { // 总数 err = dao.DB.Model(&model.Favorite{}).Preload("User"). Where("user_id=?", uId).Count(&total).Error if err != nil { return } err = dao.DB.Model(&model.Favorite{}). Joins("AS f LEFT JOIN user AS u on u.id = f.boss_id"). Joins("LEFT JOIN product AS p ON p.id = f.product_id"). Joins("LEFT JOIN category AS c ON c.id = p.category_id"). Where("f.user_id = ?", uId). Offset((pageNum - 1) * pageSize).Limit(pageSize). Select("f.user_id AS user_id," + "f.product_id AS product_id," + "UNIX_TIMESTAMP(f.created_at) AS created_at," + "p.title AS title," + "p.info AS info," + "p.name AS name," + "c.id AS category_id," + "c.category_name AS category_name," + "u.id AS boss_id," + "u.user_name AS boss_name," + "u.avatar AS boss_avatar," + "p.price AS price," + "p.img_path AS img_path," + "p.discount_price AS discount_price," + "p.num AS num," + "p.on_sale AS on_sale"). Find(&r).Error