Association mode provides a set of helper methods for working with relationships on an already-loaded model instance. Access it by callingDocumentation Index
Fetch the complete documentation index at: https://mintlify.com/go-gorm/gorm/llms.txt
Use this file to discover all available pages before exploring further.
db.Model(&record).Association("FieldName").
You must have a loaded model value (with a valid primary key) before calling
Association. GORM uses the model’s primary key to scope all queries.Find
Retrieve all records associated with the model:Append
Add new associated records without removing existing ones:For
has one and belongs to associations, Append behaves identically to Replace — it replaces the current associated record rather than adding to it.Replace
Swap out all current associations with a new set:has one and has many, the old associated records have their foreign keys set to NULL. For many to many, the old join table rows are deleted.
Delete
Remove specific records from the association:Delete only removes the association link:
- For
has one/has many: sets the foreign key toNULL. - For
many to many: deletes the join table row. - For
belongs to: sets the foreign key on the owner toNULL.
Unscoped.
Clear
Remove all associations from the model:Clear is equivalent to calling Replace with no arguments.
Count
Return the number of associated records:Unscoped
By default,Delete and Clear only unlink associations (set foreign keys to NULL or delete join rows). Use Unscoped() to permanently delete the associated records themselves:
Unscoped also makes Find return soft-deleted records:
Batch operations
All Association methods support batch operations when the model is a slice. Each element in the model slice maps positionally to the corresponding element in the values slice:Error handling
Association mode collects errors on theAssociation.Error field. Check it after retrieving the association handle:
Common errors
Common errors
ErrUnsupportedRelation— the field name passed toAssociation()does not correspond to any defined relationship on the model’s schema.ErrPrimaryKeyRequired— the model value does not have a primary key set. Ensure you load the record from the database before callingAssociation.ErrInvalidValueOfLength— for batch operations, the values slice length does not match the model slice length.ErrInvalidValue— a non-addressable value was passed toAppendorReplacefor a struct-typed relationship.
Quick reference
Find
Retrieve associated records, with optional extra conditions.
Append
Add one or more records to the association without removing existing ones.
Replace
Swap the entire association set with a new one.
Delete
Remove specific records from the association link.
Clear
Remove all association links for this model.
Count
Return the number of associated records.