Golang gorm many2many query

many-to-many relationship


Many-to-many relationship, need to use the third table to store the relationship between the two tables

 For many-to-many, the many2many tag must be added. article_tags is used to specify the third table,

package main

import (
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

type Tag struct {
	ID       uint
	Name     string
	Articles []Article `gorm:"many2many:articles_tags;"`
}

type Article struct {
	ID    uint
	Title string
	Tags  []Tag `gorm:"many2many:articles_tags;"`
}

func main() {
	dsn := "root:7PXjAkY!&nlR@tcp(192.168.11.128:3306)/test?charset=utf8mb4&parseTime=True&loc=Local"
	db, _ := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	db.AutoMigrate(&Article{}, &Tag{})
	db.Create(&Article{
		Title: "python基础",
		Tags: []Tag{
			{Name: "python"},
			{Name: "后端"},
		},
	})
}
mysql> select * from articles;
+----+--------------+
| id | title        |
+----+--------------+
|  2 | python?虹?   |
+----+--------------+

mysql> select * from tags;
+----+--------+
| id | name   |
+----+--------+
|  1 | python |
|  2 | ?..   |
+----+--------+


mysql> select * from articles_tags;
+--------+------------+
| tag_id | article_id |
+--------+------------+
|      1 |          2 |
|      2 |          2 |
+--------+------------+

An article and two tags are created, and their dependencies are also created. The third table will create itself.

If you want to associate an existing article, you have to check it first.

	var tags []Tag
	db.Find(&tags, "name in ?", []string{"python"})

	db.AutoMigrate(&Article{}, &Tag{})
	db.Create(&Article{
		Title: "golang",
		Tags:  tags,
	})



mysql> select * from articles_tags;
+--------+------------+
| tag_id | article_id |
+--------+------------+
|      1 |          2 |
|      2 |          2 |
|      1 |          4 |
+--------+------------+

mysql> select * from tags;
+----+--------+
| id | name   |
+----+--------+
|  1 | python |
|  2 | ?..   |
+----+--------+

mysql> select * from articles;
+----+--------------+
| id | title        |
+----+--------------+
|  2 | python?虹?   |
|  3 | golang       |
|  4 | golang       |
+----+--------------+

 

 

 

 

Guess you like

Origin blog.csdn.net/qq_34556414/article/details/132311295