Gorm relation, one to one, one to many, many to many query


Functions to be realized
Articles belong to a category
The article has multiple tags

There are four related tables. The tables are established in the database in advance. There is no foreign key relationship

  • Article table
  • Tag table
  • article_ Tag table
  • Category table
//Article table
type Article struct {
  Id int `json:"id"`
  Title string `json:"title"`
  CategoryId int `json:"category_id"`
  Category Category `json:"category"; Gorm: "ForeignKey: categoryid" ` // specify the associated foreign key
  Tag [] tag ` Gorm: "many2any: article_tag" JSON: "tag" ` // many to many relationship
  //article_ Tag table default article_ The ID field corresponds to the article table id.tag_ The ID field corresponds to the ID of the tag table
  //You can print the corresponding SQL log for debugging
//Articles_ Label middle table
type ArticleTag struct {
   Id int `json:"id" `
  ArticleId string `json:"article_id"`
  TagId string `json:"tag_id"`
  CreatedAt string `json:"created_at"`
  UpdatedAt string `json:"updated_at"`
//Label table
type Tag struct {
   Id int `json:"id" `
  TagName string `json:"tag_name"`
//Classification table
type Category struct {
   ID int `json:"id"`
  CategoryName string `json:"category_name"`
  Status int `json:"status"`
  CreatedAt time.Time `json:"created_at"`
  UpdatedAt time.Time `json:"updated_at"`
//Remote one to many. One to one
func (a *Article) ListArticle(title string) (Article, error) {
   query := database.GormPool
  var article Article
  query.Where("title like ?", "%"+title+"%").First(&article)
   err := query.Model(&article).
      Related(&article.Tag, "tag").
  if err != nil && err != gorm.ErrRecordNotFound {
      return article, nil
   return article, err

The results are shown in the figure: one category, multiple labels
To use the related method, you need to query the article first,
Then find the category according to the category ID specified in the article definition,
Find the tag, directly define the tag, receive the tag slice, and then write the table correspondence of Gorm: “many2any: article_tag”
Gorm relation, one to one, one to many, many to many query

func (a *Article) ListArticle(title string) (articles []Article, err error) {
    query := database.GormPool
    err = query.Model(articles).
        Where("title like ?", "%"+title+"%").
    if err != nil && err != gorm.ErrRecordNotFound {

Using the preload method, you can directly use the above search method. The results are as follows
Gorm relation, one to one, one to many, many to many query
If there are any mistakes in the above content, or you don’t understand, please communicate at any time. Make progress together

This work adoptsCC agreement, reprint must indicate the author and the link to this article


Recommended Today

Seven Python code review tools recommended

althoughPythonLanguage is one of the most flexible development languages at present, but developers often abuse its flexibility and even violate relevant standards. So PythoncodeThe following common quality problems often occur: Some unused modules have been imported Function is missing arguments in various calls The appropriate format indentation is missing Missing appropriate spaces before and after […]