Has One
A has one
association also sets up a one-to-one connection with another model, but with somewhat different semantics (and consequences). This association indicates that each instance of a model contains or possesses one instance of another model.
For example, if your application includes users and credit cards, and each user
can only have one credit card.
// User has one CreditCard, CreditCardID is the foreign key |
Foreign Key
For a has one
relationship, a foreign key field must also exist, the owned
will save the primary key of the model belongs to it into this field.
The field’s name is usually generated with has one
model’s type plus itsprimary key
, for the above example it is UserID
.
When you give a credit card to the user, its will save the User’s ID
into itsUserID
field.
If you want to use another field to save the relationship, you can change it
with tag foreignkey
, e.g:
type CreditCard struct { |
Association ForeignKey
By default, the owned entity will save the has one
model’s primary into a
foreign key, you could change to save another field, like use Name
for below
example.
type CreditCard struct { |
Polymorphism Association
Supports polymorphic has many
and has one
associations.
type Cat struct { |
Note: polymorphic belongs-to and many-to-many are explicitly NOT supported, and will throw errors.
Working with Has One
You could find has one
associations with Related
var card CreditCard |
For advanced usage, refer Association Mode