Chapters
1. Types of Associations
1.1. The BelongsTo
Association
Owner := activerecord.New("owner", func(r *activerecord.R) {
r.BelongsTo("target")
})
If you want to access the associated record, use the Association
method:
target := Owner.Association("target")
fmt.Println(target) // Ok(Some(<#Target id: 2, name: "Bill">))
1.2. The HasOne
Association
Owner := activerecord.New("owner", func(r *activerecord.R) {
r.HasOne("target")
})
target := Owner.Association("target")
fmt.Println(target) // Ok(Some(<#Target id: 4, owner_id: 5, name: "John"))
1.3. The HasMany
Association
Owner := activerecord.New("owner", func(r *activerecord.R) {
r.HasMany("targets")
})
If you want to access the collection of association records, use the Collection
method:
targets := Owner.Collection("targets")
fmt.Println(targets.First()) // #<Target id: 3, owner_id: 1, name: "Elon">