多对多关系
多对多关系,需要用第三张表存储两张表的关系
多对多就必须得加上many2many的tag。article_tags是用来指定第三张表,
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 |
+--------+------------+
创建了一篇文章和两个tag,同时还会去创建其依赖关系。第三张表会自己去创建。
关联已有文章就得先查。
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 |
+----+--------------+