Gin framework of go language + mysql to do web development, the relationship between models

gin framework of go language + mysql to do web development, the association between models, here is an example:

package model

import "time"

// Article 
type Article struct {
    ID            uint       `gorm:"primary_key" json:"id"`
    CreatedAt     time.Time  `json:"createdAt"`
    UpdatedAt     time.Time  `json:"updatedAt"`
    DeletedAt     *time.Time `sql:"index" json:"deletedAt"`
    Name          string     `json:"name"`
    BrowseCount   uint       `json:"browseCount"`
    CommentCount  uint       `json:"commentCount"`
    CollectCount  uint       `json:"collectCount"`
    Status        int        `json:"status"`
    Content       string     `json:"content"`
    HTMLContent   string     `json:"htmlContent"`
    ContentType   int        `json:"contentType"`
    Categories    []Category `gorm:"many2many:article_category;ForeignKey:ID;AssociationForeignKey:ID" json:"categories"`
    Comments      []Comment  `gorm:"ForeignKey:SourceID" json:"comments"`
    UserID        uint       `json:"userID"`
    User          User       `json:"user"`
    LastUserID    uint       `json:"lastUserID"` //
    LastUser      User       `json:"lastUser"`
    LastCommentAt *time.Time `json:"lastCommentAt"`
}

question:
1, User and Article have an one-to-many relationship. I don"t quite understand why the above code should write User and UserID , just UserID .
2. Write User here, meaning that the articles table has a user field to hold the information about this user?

add:
the sql code for creating the table does not write the user field, so why should the above Article structure be written with User??

clipboard.png

Jan.08,2022

The code posted by

@ cherrylee is a mixed data structure of service & model. Is that what you want?

  

may be used for caching and appropriate redundancy to avoid each associated query;
may also be required to bring User content with the output json here. After the structure is filled with USer, you can directly marshal to json

.
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b3d7da-2c38d.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b3d7da-2c38d.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?