+
Skip to content

a two-way relation makes dirty data when inserting one model #7503

Open
@chanmaoganda

Description

@chanmaoganda

Your Question

a two-way relation makes dirty data when inserting one model

how to reproduce:

open any db, use auto migrate to migrate tables

type Meeting struct {
	MeetingId    int       `gorm:"primaryKey"`
	MeetingNo    string    `gorm:"unique;not null"`
	BookedBy     int       `gorm:"not null"`
	BookedByName string    `gorm:"size:64;not null" comment:"who has booked this meeting"`
	MeetingState string    `gorm:"size:4;not null"`
	ScheduledAt  time.Time `gorm:"not null"`
	EndedAt      time.Time `gorm:"not null"`
	Users        []User    `gorm:"many2many:user_meeting_rule"`
}

type User struct {
	UserId    int       `gorm:"primaryKey"`
	Username  string    `gorm:"unique;not null"`
	Password  string    `gorm:"not null"`
	Phone     string    `gorm:"unique;not null"`
	Email     string    `gorm:"unique;not null"`
	CreatedAt time.Time `gorm:"not null"`
	Meetings  []Meeting `gorm:"many2many:user_meeting_rule"`
}

if i try to insert a meeting with users, gorm will first insert user in any ways

logs:

2025/07/03 11:54:57 C:/Users/matebook/Codes/rendezvous/internal/store/dbstore/meeting.go:39
[4.056ms] [rows:0] INSERT INTO "users" ("username","password","phone","email","created_at","user_id") VALUES ('ethan','1','2','1','2025-01-01 00:00:00',1) ON CONFLICT DO NOTHING RETURNING "user_id"

2025/07/03 11:54:57 C:/Users/matebook/Codes/rendezvous/internal/store/dbstore/meeting.go:39
[5.595ms] [rows:1] INSERT INTO "user_meeting_rule" ("meeting_meeting_id","user_user_id") VALUES (1,1) ON CONFLICT DO NOTHING

2025/07/03 11:54:57 C:/Users/matebook/Codes/rendezvous/internal/store/dbstore/meeting.go:39
[58.662ms] [rows:1] INSERT INTO "meetings" ("meeting_no","booked_by","booked_by_name","meeting_state","scheduled_at","ended_at") VALUES ('6VYkJ92S',1,'ethan','1','2006-01-02 15:04:05','2006-01-03 15:04:05') RETURNING "meeting_id"
{"time":"2025-07-03T11:54:57.3330097+08:00","id":"","remote_ip":"127.0.0.1","host":"127.0.0.1:8080","method":"POST","uri":"/api/v1/meeting","user_agent":"PostmanRuntime/7.44.1","status":200,"error":"","latency":68229100,"latency_human":"68.2291ms","bytes_in":123,"bytes_out":32}

What is expected?

it should only insert middle table, not inserting user

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions

    点击 这是indexloc提供的php浏览器服务,不要输入任何密码和下载