Five Tips on How to Use Gorm Better

Francesco Pastore
3 min readNov 1, 2022

Gorm is one of the most used ORMs for the Go language. It is complete and very easy to use. But sometimes the documentation does not cover all the cases.

There are some functionalities that once known can help you to write better code and simplify your work. Let's see five tips on how to use Gorm better.

1. Use custom foreign key constraints

When you create relations between tables remember to update the constraints on the foreign keys. As default, Gorm set the mode “NO ACTION” for update and delete cases.

However, you could make your life easier by using specific modes like for example the “CASCADE” one. Every time a primary key is updated the relative foreign key will be too. Instead, if a referenced record is deleted also the rows that reference it will be deleted as well.

In PostgreSQL, the available constraints are:

  • SET NULL: set the foreign key to null
  • CASCADE: do the same action as done on the referenced row.
  • SET DEFAULT: set the foreign key to the default value (null or empty if not specified)
  • NO ACTION and RESTRICT: in few words, they do not allow some operations on the referenced row. Look to the documentation to read more details about them.

--

--

Francesco Pastore
Francesco Pastore

Written by Francesco Pastore

An engineering student in Milan and a web developer for an IT company. Write about programming and cybersecurity topics.

No responses yet