2

I deleted the object and want it's ID deleted too in a relationship table. How do I do it? i.e. objects with relations are deleted but the tables of their relations remain.

enter image description here

Also wanted to ask, GORM is the best ORM solution for Go-Gin ?

oguz ismail
  • 1
  • 16
  • 47
  • 69
atkisai
  • 53
  • 3
  • 7
  • I think you're asking about [cascading deletes](https://stackoverflow.com/questions/6260688/how-do-i-use-cascade-delete-with-sql-server#6260736) which is more about SQL than Go, but I'm not sure. Can you provide a more concrete example? As for the "best tool" question, [we avoid best/favorite sorts of questions](https://stackoverflow.com/help/dont-ask); the answer depends on what you're doing. – Schwern Apr 19 '19 at 16:30
  • I misspoke, ORMs can do their own cascading deletes. I don't know if GORM can. – Schwern Apr 19 '19 at 16:37
  • There are tables in which relations of objects are registered by means of them id. When deleting objects, these relationships remain thereby simply taking up space on the server. I don’t know how to access these tables from the code in order to manually delete them, since these tables are created automatically and aren’t present in my models. – atkisai Apr 19 '19 at 16:40
  • "Relations of objects registered by means of their id" sounds like [foreign keys](https://www.w3schools.com/sql/sql_foreignkey.asp). But it sounds like your schema does not properly declare its foreign keys. This is unfortunately common. Foreign keys would prevent you from deleting the object while leaving references around. Declaring foreign keys as "on delete cascade" would delete the referencing rows when you delete the primary object. I'd suggest you read into a SQL tutorial on cascading deletes. – Schwern Apr 19 '19 at 21:04

1 Answers1

1

Try explicitly adding foreign keys and ON DELETE CASCADE to your models. I've found that GORM can be iffy when it cones to this kind of thing, but doing it explicitly seems to always make it work.

For example:

type Person struct {
    ID      int
    Bio     Biography `gorm:"Foreignkey:PersonID;"`
    Name    string
}

type Biography struct {
    ID       int
    Content  string
    PersonID int    `sql:"type:bigint REFERENCES people(id) ON DELETE CASCADE"`
}

Note: you have to specify what the actual database column and table will be called, not the field. Since GORM automatically pluralizes and converts tables to snake_case, I reference the column people(id). If you overwrite this functionality, use whatever table and column name you have.

robbieperry22
  • 1,753
  • 1
  • 18
  • 49