Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package services
- import (
- "fmt"
- "gorm.io/gorm"
- )
- type Article struct {
- gorm.Model
- AuthorID uint
- Title string
- Content string
- Image string
- ReadTime int
- Claps int
- }
- func GetArticlesService(db *gorm.DB) ([]Article, error) {
- var articles []Article
- result := db.Preload("User").Find(&articles)
- //result := db.Find(&articles)
- fmt.Println("result:", result)
- if result.Error != nil {
- return nil, fmt.Errorf("failed to retrieve articles: %w", result.Error)
- }
- return articles, nil
- }
- User model:
- package models
- import "gorm.io/gorm"
- type User struct {
- gorm.Model
- Name string `json:"name" gorm:"not null"`
- Email string `json:"email" gorm:"not null;unique"`
- Password string `json:"password" gorm:"not null"`
- Image string `json:"image"`
- Description string `json:"description" gorm:"not null"`
- }
- Article model:
- package models
- import "gorm.io/gorm"
- type Article struct {
- gorm.Model
- AuthorID uint `json:"author_id" gorm:"foreignKey;references:users(id)"`
- Title string `json:"title" gorm:"not null"`
- Content string `json:"content" gorm:"not null"`
- Image string `json:"image"`
- ReadTime int `json:"read_time" gorm:"not null"`
- Claps int `json:"claps"`
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement