1

In the GORM documentation for reference and foreign key

https://gorm.io/docs/belongs_to.html

What does a foreign key do?

what does a reference do?

What is the difference between a foreign key and reference?

1
  • Reference is more of a ORM thing. It instructs the ORM that the tables are linked by which column, along with some convention baked into ORM. Essentially establishing the relationship at the ORM level. Foreign key is more of a database constraint. I suggest you look at the docs from ActiveRecord in Rails. The concept is mostly the same, it just has better docs. guides.rubyonrails.org/association_basics.html and stackoverflow.com/questions/46091963/… Commented Oct 14, 2024 at 0:36

1 Answer 1

0

Using the example in the link you provided, User belongs to Company and CompanyID is the foreign key

The foreign key is a field in the child model (e.g., User.CompanyID) that stores the ID of the related parent model (e.g., Company.ID), linking the two models.

The references tag tells GORM which field in the parent model (e.g., Company.Code) the foreign key should reference, instead of the default primary key (ID).

Sign up to request clarification or add additional context in comments.

1 Comment

What difference does it make whether it refers to the main key or not, and what are its advantages or disadvantages compared to the other one

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.