Delete removes only the data in the intermediate table and deletes the original
var a Article1
db.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 first gets this table,
(2) Association then connects the third table of tags
(3) After that, the most critical thing is what operation to perform. Here is delete. Who should be deleted? What is deleted is the tag associated with the article.
var a Article1
db.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 |
+-------------+---------+
Add using Append as above
var t []Tag1
db.Find(&t)
var a Article1
db.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 Tag1
db.Take(&t, 1)
var a Article1
db.Preload("Tag1s").Take(&a, 2)
db.Model(&a).Association("Tag1s").Replace(&t)
fmt.Printf("%v", a)
{2 golang [{1 cloud []}]}