Advertisement
Guest User

Untitled

a guest
Mar 23rd, 2024
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.26 KB | None | 0 0
  1. package services
  2.  
  3. import (
  4. "fmt"
  5. "gorm.io/gorm"
  6. )
  7.  
  8. type Article struct {
  9. gorm.Model
  10. AuthorID uint
  11. Title string
  12. Content string
  13. Image string
  14. ReadTime int
  15. Claps int
  16. }
  17.  
  18. func GetArticlesService(db *gorm.DB) ([]Article, error) {
  19. var articles []Article
  20.  
  21. result := db.Preload("User").Find(&articles)
  22. //result := db.Find(&articles)
  23.  
  24. fmt.Println("result:", result)
  25.  
  26. if result.Error != nil {
  27. return nil, fmt.Errorf("failed to retrieve articles: %w", result.Error)
  28. }
  29.  
  30. return articles, nil
  31. }
  32.  
  33. User model:
  34. package models
  35.  
  36. import "gorm.io/gorm"
  37.  
  38. type User struct {
  39. gorm.Model
  40. Name string `json:"name" gorm:"not null"`
  41. Email string `json:"email" gorm:"not null;unique"`
  42. Password string `json:"password" gorm:"not null"`
  43. Image string `json:"image"`
  44. Description string `json:"description" gorm:"not null"`
  45. }
  46.  
  47. Article model:
  48. package models
  49.  
  50. import "gorm.io/gorm"
  51.  
  52. type Article struct {
  53. gorm.Model
  54. AuthorID uint `json:"author_id" gorm:"foreignKey;references:users(id)"`
  55. Title string `json:"title" gorm:"not null"`
  56. Content string `json:"content" gorm:"not null"`
  57. Image string `json:"image"`
  58. ReadTime int `json:"read_time" gorm:"not null"`
  59. Claps int `json:"claps"`
  60. }
  61.  
  62.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement