Delete 移除 只删除中间表的数据 删除原有的
var a Article1db.Preload("Tag1s").Take(&a, 1)fmt.Printf("%v", a)
{1 k8s [{1 cloud []} {2 linux []}]}mysql> select * from article1;
+----+--------+
| id | title |
+----+--------+
| 1 | k8s |
| 2 | golang |
+----+--------+mysql> select * from tag1;
+----+-------+
| id | name |
+----+-------+
| 1 | cloud |
| 2 | linux |
+----+-------+mysql> select * from article_tags;
+-------------+---------+
| article1_id | tag1_id |
+-------------+---------+
| 1 | 1 |
| 1 | 2 |
| 2 | 2 |
+-------------+---------+
(1)model 先拿到这张表,
(2)Association然后去连接tags第三张表
(3)之后就是最关键的要去执行什么操作,这里是delete,删除谁呢?删除的就是article关联的tag。
var a Article1db.Preload("Tag1s").Take(&a, 1)db.Model(&a).Association("Tag1s").Delete(a.Tag1s)fmt.Printf("%v", a){1 k8s []}mysql> select * from tag1;
+----+-------+
| id | name |
+----+-------+
| 1 | cloud |
| 2 | linux |
+----+-------+mysql> select * from article1;
+----+--------+
| id | title |
+----+--------+
| 1 | k8s |
| 2 | golang |
+----+--------+mysql> select * from article_tags;
+-------------+---------+
| article1_id | tag1_id |
+-------------+---------+
| 2 | 2 |
+-------------+---------+
添加 和上面一样使用Append
var t []Tag1db.Find(&t)var a Article1db.Preload("Tag1s").Take(&a, 1)db.Model(&a).Association("Tag1s").Append(&t)fmt.Printf("%v", a){1 k8s [{1 cloud []} {2 linux []}]}mysql> select * from article1;
+----+--------+
| id | title |
+----+--------+
| 1 | k8s |
| 2 | golang |
+----+--------+mysql> select * from tag1;
+----+-------+
| id | name |
+----+-------+
| 1 | cloud |
| 2 | linux |
+----+-------+mysql> select * from article_tags;
+-------------+---------+
| article1_id | tag1_id |
+-------------+---------+
| 1 | 1 |
| 1 | 2 |
| 2 | 2 |
+-------------+---------+
Replace 替换
var t Tag1db.Take(&t, 1)var a Article1db.Preload("Tag1s").Take(&a, 2)db.Model(&a).Association("Tag1s").Replace(&t)fmt.Printf("%v", a){2 golang [{1 cloud []}]}