Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

401
Views
La relación bidireccional many2many en gorm no funciona correctamente

Resumen

Intenté implementar DUPLICATE: solución de relación bidireccional many2many . Después de agregar diferentes usuarios a los campos "Seguidores "Followings" y "Followers" , cualquier usuario agregado al campo Following también se agrega al campo Followers , y viceversa. Lo mismo ocurre con los campos BlockedBy y Blocking .

Definí los tipos de estructura de Following y Blocking User de la siguiente manera

 type User struct { Email string `gorm:"size:100;not null;unique" json:"email"` ... UserId string `gorm:"primary_key;not null" json:"userid"` } type Following struct { ID string `gorm:"primary_key" json:"id"` User User `gorm:"foreignKey:ID;references:UserId"` Followings []*User `gorm:"many2many:user_relation;foreignKey:ID;joinForeignKey:UserA;references:UserId;joinReferences:UserB;constraint:OnDelete:CASCADE"` Followers []*User `gorm:"many2many:user_relation;foreignKey:ID;joinForeignKey:UserB;references:UserId;joinReferences:UserA;constraint:OnDelete:CASCADE"` } type Blocking struct { ID string `gorm:"primary_key" json:"id"` User User `gorm:"foreignKey:ID"` BlockedBy []*User `gorm:"many2many:user_blocks;foreignKey:ID;joinForeignKey:UserIdBlocked;joinReferences:UserId;constraint:OnDelete:CASCADE"` Blocking []*User `gorm:"many2many:user_blocks;foreignKey:ID;joinForeignKey:UserId;joinReferences:userIdBlocked;constraint:OnDelete:CASCADE"` }

método de carga

Así es como inicialicé y cargué algunos datos por primera vez con fines de prueba: // La carga genera automáticamente las tablas y los registros

 func Load() { db, err := database.Connect() if err != nil { log.Fatal(err) } defer db.Close() // Creates table for each model err = db.Debug().DropTableIfExists( &models.User{}, &models.Following{}, &models.Blocking{}, ).Error if err != nil { log.Fatal(err) } //ERROR while using Postgres on Post model err = db.Debug().AutoMigrate( &models.User{}, &models.Following{}, &models.Blocking{}, ).Error if err != nil { log.Fatal(err) } for i, _ := range users { err = db.Debug().Model(&models.User{}).Create(&users[i]).Error if err != nil { log.Fatal(err) } userfollowings[i].ID = users[i].UserId blocked_users[i].ID = users[i].UserId err = db.Debug().Model(&models.Following{}).Create(&userfollowings[i]).Error if err != nil { log.Fatal(err) } blocked_users[i].ID = users[i].UserId err = db.Debug().Model(&models.Blocking{}).Create(&blocked_users[i]).Error if err != nil { log.Fatal(err) } err = db.Debug().Model(&userfollowings[i]).Related(&userfollowings[i].User, "user_id").Error if err != nil { log.Fatal(err) } err = db.Debug().Model(&blocked_users[i]).Related(&blocked_users[i].User, "user_id").Error if err != nil { log.Fatal(err) } if i == 0 { err = db.Model(&userfollowings[i]).Association("Followings").Append(&users[1], &users[2]).Error if err != nil { log.Fatal(err) } } else if i == 1 { err = db.Model(&userfollowings[i]).Association("Followings").Append(&users[2]).Error if err != nil { log.Fatal(err) } } else if i == 2 { err = db.Model(&userfollowings[i]).Association("Followings").Append(&users[3]).Error if err != nil { log.Fatal(err) } } else if i == 3 { err = db.Model(&userfollowings[i]).Association("Followings").Append(&users[0]).Error if err != nil { log.Fatal(err) } fo_info := models.Following{} if err != nil { log.Fatal(err) } console.Pretty(&fo_info) } } }

Mostrando el siguiente resultado de consulta del modelo para UserId: 4

 [2021-12-27 12:17:03] [0.90ms] SELECT * FROM `users` INNER JOIN `user_relation` ON `user_relation`.`user_user_id` = `users`.`user_id` WHERE (`user_relation`.`following_id` IN ('4')) [0 rows affected or returned ] { "id": "4", "User": { "email": "q4@gmail.com", "id": "4", "displayName": "John Lennon", }, "Followings": [ { "email": "q@gmail.com", ..., "userid": "1", "displayName": "Ringo Starr", }, ], "Followers": [ { "email": "q@gmail.com", ... "userid": "1", "displayName": "Ringo Starr", } ] }

Resultado Esperado

 [2021-12-27 12:17:03] [0.90ms] SELECT * FROM `users` INNER JOIN `user_relation` ON `user_relation`.`user_user_id` = `users`.`user_id` WHERE (`user_relation`.`following_id` IN ('4')) [0 rows affected or returned ] { "id": "4", "User": { "email": "q4@gmail.com", "id": "4", "displayName": "John Lennon", }, "Followings": [ { "email": "q@gmail.com", ..., "userid": "1", "displayName": "Ringo Starr", }, ], "Followers": [ { "email": "q2@gmail.com", ... "userid": "2", "displayName": "George Harrison", } ] }

Desde el viernes pasado, no puedo hacer que esto funcione. Probé diferentes recursos de la documentación de Golang Gorm y busqué preguntas y respuestas SOF similares, que no me proporcionaron ninguna solución ni orientación.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

relacion muchos a muchos no funciona correctamente

over 4 years ago · Elkin Alfonso Rey Ladino Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!