association

package
v0.15.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 14, 2026 License: AGPL-3.0 Imports: 6 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Association

type Association struct {
	// contains filtered or unexported fields
}

Association represents a model association. This is the base type for all relationship types (belongs-to, has-many, has-one, polymorphic). It provides common functionality for managing relationships between models.

Example:

type User struct {
    ID       uint
    Name     string
    Profile  *Profile
    Posts    []Post
}

// The Profile and Posts fields would be managed through Association instances

func NewAssociation

func NewAssociation(query contractsorm.Query, model any, association string) *Association

NewAssociation creates a new Association instance. The query parameter provides the query builder for database operations. The model parameter is the model instance this association belongs to. The association parameter is the name of the association (e.g., "profile", "posts").

Example:

user := User{ID: 1, Name: "John"}
assoc := NewAssociation(db.Query(), &user, "profile")

func (*Association) Append

func (a *Association) Append(values ...any) error

Append appends a model to the association. The values parameter provides the model(s) to append to the association. This is a base implementation - specific relationship types override this.

Example:

err := assoc.Append(&Post{Title: "New Post"})

func (*Association) AssociationName

func (a *Association) AssociationName() string

AssociationName returns the association name.

Example:

name := assoc.AssociationName() // "profile", "posts", etc.

func (*Association) Clear

func (a *Association) Clear() error

Clear clears the association by removing all related models. This is a base implementation - specific relationship types override this.

Example:

err := assoc.Clear()

func (*Association) Count

func (a *Association) Count() int64

Count returns the number of records in the association. This is a base implementation - specific relationship types override this.

Example:

count := assoc.Count()

func (*Association) Delete

func (a *Association) Delete(values ...any) error

Delete deletes the given value from the association. The values parameter provides the model(s) to remove from the association. This is a base implementation - specific relationship types override this.

Example:

err := assoc.Delete(&Post{ID: 1})

func (*Association) Find

func (a *Association) Find(out any, conds ...any) error

Find finds records that match given conditions. The out parameter must be a pointer to a struct or slice for the results. The conds parameter provides optional WHERE conditions for the query. This is a base implementation - specific relationship types (belongs-to, has-many, has-one) override this.

Example:

var profile Profile
err := assoc.Find(&profile)

var posts []Post
err := assoc.Find(&posts, "published = ?", true)

func (*Association) Model

func (a *Association) Model() any

Model returns the model instance this association belongs to.

Example:

user := assoc.Model().(*User)

func (*Association) Query

func (a *Association) Query() contractsorm.Query

Query returns the underlying query instance. This allows direct access to the query builder for custom operations.

Example:

query := assoc.Query()
err := query.Where("status = ?", "active").Get(&results)

func (*Association) Replace

func (a *Association) Replace(values ...any) error

Replace replaces the association with the given value. The values parameter provides the new model(s) for the association. This is a base implementation - specific relationship types override this.

Example:

err := assoc.Replace(&Post{Title: "Updated Post"})

type BelongsTo

type BelongsTo struct {
	*Association
	// contains filtered or unexported fields
}

BelongsTo represents a belongs-to relationship. In a belongs-to relationship, the current model belongs to another model. The foreign key is stored on the current model's table.

Example: An Address belongs to a User.

  • addresses table has user_id foreign key
  • users table has id primary key

Database Schema:

users (id, name, email)
addresses (id, user_id, street, city)

type Address struct {
    ID     uint
    UserID uint // foreign key
    User   User // belongs-to relationship
}

func NewBelongsTo

func NewBelongsTo(query contractsorm.Query, model any, association, foreignKey, otherKey string) *BelongsTo

NewBelongsTo creates a new BelongsTo association. The query parameter provides the query builder for database operations. The model parameter is the model instance that belongs to another model. The association parameter is the name of the association (e.g., "user"). The foreignKey parameter is the foreign key column on the current model (e.g., "user_id"). The otherKey parameter is the primary key column on the related model (e.g., "id").

Example:

address := Address{ID: 1, UserID: 5}
assoc := NewBelongsTo(db.Query(), &address, "user", "user_id", "id")

func (*BelongsTo) Append

func (b *BelongsTo) Append(values ...any) error

Append sets the foreign key to associate the model. The values parameter must contain exactly one model to associate with. Sets the foreign key on the current model to the related model's primary key. Saves the current model to persist the foreign key change.

Example:

user := User{ID: 5, Name: "John"}
err := assoc.Append(&user)

func (*BelongsTo) Clear

func (b *BelongsTo) Clear() error

Clear clears the association by setting the foreign key to nil. Sets the foreign key on the current model to nil/zero value. Saves the current model to persist the change.

Example:

err := assoc.Clear()

func (*BelongsTo) Count

func (b *BelongsTo) Count() int64

Count returns 1 if the association exists, 0 otherwise. Checks if the foreign key is set and the related record exists.

Example:

count := assoc.Count() // 1 if associated, 0 if not

func (*BelongsTo) Delete

func (b *BelongsTo) Delete(values ...any) error

Delete clears the association by setting the foreign key to nil. The values parameter is validated to ensure the provided value matches the current association. Sets the foreign key on the current model to nil/zero value. Saves the current model to persist the change.

Example:

user := User{ID: 5}
err := assoc.Delete(&user)

func (*BelongsTo) Find

func (b *BelongsTo) Find(out any, conds ...any) error

Find loads the associated model for a belongs-to relationship. The out parameter must be a pointer to a struct for the related model. The conds parameter provides optional WHERE conditions for the query. Queries the related table where its primary key equals the foreign key value.

Example:

var user User
err := assoc.Find(&user)

var user User
err := assoc.Find(&user, "status = ?", "active")

func (*BelongsTo) Replace

func (b *BelongsTo) Replace(values ...any) error

Replace replaces the current association with the given value. The values parameter must contain exactly one model to associate with. This is equivalent to Append for belongs-to relationships.

Example:

user := User{ID: 10, Name: "Jane"}
err := assoc.Replace(&user)

type HasMany

type HasMany struct {
	*Association
	// contains filtered or unexported fields
}

HasMany represents a has-many relationship. In a has-many relationship, the current model has many related models. The foreign key is stored on the related model's table.

Example: A User has many Posts.

  • users table has id primary key
  • posts table has user_id foreign key

Database Schema:

users (id, name, email)
posts (id, user_id, title, content)

type User struct {
    ID    uint
    Name  string
    Posts []Post // has-many relationship
}

func NewHasMany

func NewHasMany(query contractsorm.Query, model any, association, foreignKey, localKey string) *HasMany

NewHasMany creates a new HasMany association. The query parameter provides the query builder for database operations. The model parameter is the model instance that has many related models. The association parameter is the name of the association (e.g., "posts"). The foreignKey parameter is the foreign key column on the related model (e.g., "user_id"). The localKey parameter is the primary key column on the current model (e.g., "id").

Example:

user := User{ID: 1, Name: "John"}
assoc := NewHasMany(db.Query(), &user, "posts", "user_id", "id")

func (*HasMany) Append

func (h *HasMany) Append(values ...any) error

Append appends models to the association. The values parameter provides the model(s) to append to the association. Sets the foreign key on each related model to the current model's local key value. Saves each related model to persist the foreign key change.

Example:

post1 := Post{Title: "First Post"}
post2 := Post{Title: "Second Post"}
err := assoc.Append(&post1, &post2)

func (*HasMany) Clear

func (h *HasMany) Clear() error

Clear clears the association by setting the foreign key to null for all related models. Updates all related models to set foreign key to null.

Example:

err := assoc.Clear()

func (*HasMany) Count

func (h *HasMany) Count() int64

Count returns the number of records in the association. Counts records where the foreign key equals the local key value.

Example:

count := assoc.Count()

func (*HasMany) Delete

func (h *HasMany) Delete(values ...any) error

Delete removes the given values from the association. The values parameter provides the model(s) to remove from the association. Sets the foreign key to null for each related model using direct SQL update. Ensures the model belongs to this association by checking the foreign key.

Example:

post := Post{ID: 1}
err := assoc.Delete(&post)

func (*HasMany) Find

func (h *HasMany) Find(out any, conds ...any) error

Find loads the associated models for a has-many relationship. The out parameter must be a pointer to a slice for the related models. The conds parameter provides optional WHERE conditions for the query. Queries the related table where the foreign key equals the local key value. Only includes records where the foreign key is not null.

Example:

var posts []Post
err := assoc.Find(&posts)

var posts []Post
err := assoc.Find(&posts, "published = ?", true)

func (*HasMany) Replace

func (h *HasMany) Replace(values ...any) error

Replace replaces the current association with the given values. The values parameter provides the new model(s) for the association. First clears the current association by setting foreign keys to null. Then appends the new values.

Example:

posts := []Post{{Title: "New Post"}, {Title: "Another Post"}}
err := assoc.Replace(posts...)

type HasOne

type HasOne struct {
	*Association
	// contains filtered or unexported fields
}

HasOne represents a has-one relationship. In a has-one relationship, the current model has one related model. The foreign key is stored on the related model's table. Similar to has-many, but only one related record is expected.

Example: A User has one Profile.

  • users table has id primary key
  • profiles table has user_id foreign key (unique)

Database Schema:

users (id, name, email)
profiles (id, user_id, bio, avatar)

type User struct {
    ID      uint
    Name    string
    Profile *Profile // has-one relationship
}

func NewHasOne

func NewHasOne(query contractsorm.Query, model any, association, foreignKey, localKey string) *HasOne

NewHasOne creates a new HasOne association. The query parameter provides the query builder for database operations. The model parameter is the model instance that has one related model. The association parameter is the name of the association (e.g., "profile"). The foreignKey parameter is the foreign key column on the related model (e.g., "user_id"). The localKey parameter is the primary key column on the current model (e.g., "id").

Example:

user := User{ID: 1, Name: "John"}
assoc := NewHasOne(db.Query(), &user, "profile", "user_id", "id")

func (*HasOne) Append

func (h *HasOne) Append(values ...any) error

Append appends a model to the association. The values parameter must contain exactly one model to associate with. Sets the foreign key on the related model to the current model's local key value. Saves the related model to persist the foreign key change.

Example:

profile := Profile{Bio: "Software Developer"}
err := assoc.Append(&profile)

func (*HasOne) Clear

func (h *HasOne) Clear() error

Clear clears the association by setting the foreign key to null. Updates the related model to set foreign key to null.

Example:

err := assoc.Clear()

func (*HasOne) Count

func (h *HasOne) Count() int64

Count returns 1 if the association exists, 0 otherwise. Counts records where the foreign key equals the local key value. Returns 1 if at least one record exists, 0 otherwise.

Example:

count := assoc.Count() // 1 if associated, 0 if not

func (*HasOne) Delete

func (h *HasOne) Delete(values ...any) error

Delete removes the given value from the association. The values parameter provides the model to remove from the association. Sets the foreign key to null for the related model using direct SQL update. Ensures the model belongs to this association by checking the foreign key.

Example:

profile := Profile{ID: 1}
err := assoc.Delete(&profile)

func (*HasOne) Find

func (h *HasOne) Find(out any, conds ...any) error

Find loads the associated model for a has-one relationship. The out parameter must be a pointer to a struct for the related model. The conds parameter provides optional WHERE conditions for the query. Queries the related table where the foreign key equals the local key value. Only includes records where the foreign key is not null. Uses First() to retrieve a single record.

Example:

var profile Profile
err := assoc.Find(&profile)

var profile Profile
err := assoc.Find(&profile, "active = ?", true)

func (*HasOne) Replace

func (h *HasOne) Replace(values ...any) error

Replace replaces the current association with the given value. The values parameter must contain exactly one model to associate with. First clears the current association by setting the foreign key to null. Then appends the new value.

Example:

profile := Profile{Bio: "Updated Bio"}
err := assoc.Replace(&profile)

type PolymorphicBelongsTo added in v0.6.0

type PolymorphicBelongsTo struct {
	*Association
	// contains filtered or unexported fields
}

PolymorphicBelongsTo represents a polymorphic belongs-to relationship. This allows a model to belong to multiple different model types. Uses polymorphic fields (ID and Type) to store the relationship.

Example: A Comment can belong to a Post or a Video.

  • comments table has commentable_id and commentable_type columns
  • commentable_id stores the ID of the related model
  • commentable_type stores the type name (e.g., "Post", "Video")

Database Schema:

posts (id, title, content)
videos (id, title, url)
comments (id, commentable_id, commentable_type, content)

type Comment struct {
    ID            uint
    CommentableID uint   // polymorphic ID
    CommentableType string // polymorphic type
}

func NewPolymorphicBelongsTo added in v0.6.0

func NewPolymorphicBelongsTo(query contractsorm.Query, model any, association, polymorphicID, polymorphicType string) *PolymorphicBelongsTo

NewPolymorphicBelongsTo creates a new PolymorphicBelongsTo association. The query parameter provides the query builder for database operations. The model parameter is the model instance that belongs to another model. The association parameter is the name of the association (e.g., "commentable"). The polymorphicID parameter is the polymorphic ID field name (e.g., "commentable_id"). The polymorphicType parameter is the polymorphic type field name (e.g., "commentable_type").

Example:

comment := Comment{ID: 1, CommentableID: 5, CommentableType: "Post"}
assoc := NewPolymorphicBelongsTo(db.Query(), &comment, "commentable", "commentable_id", "commentable_type")

func (*PolymorphicBelongsTo) Append added in v0.6.0

func (p *PolymorphicBelongsTo) Append(values ...any) error

Append sets the polymorphic fields to associate the model. The values parameter must contain exactly one model to associate with. Sets the polymorphic ID to the related model's ID. Sets the polymorphic type to the related model's type name. Saves the current model to persist the polymorphic fields.

Example:

post := Post{ID: 5, Title: "My Post"}
err := assoc.Append(&post)

func (*PolymorphicBelongsTo) Clear added in v0.6.0

func (p *PolymorphicBelongsTo) Clear() error

Clear clears the association by setting the polymorphic fields to nil. Sets the polymorphic ID and type to nil/zero values. Saves the current model to persist the changes.

Example:

err := assoc.Clear()

func (*PolymorphicBelongsTo) Count added in v0.6.0

func (p *PolymorphicBelongsTo) Count() int64

Count returns 1 if the association exists, 0 otherwise. Checks if the polymorphic ID and type are set and the related record exists.

Example:

count := assoc.Count() // 1 if associated, 0 if not

func (*PolymorphicBelongsTo) Delete added in v0.6.0

func (p *PolymorphicBelongsTo) Delete(values ...any) error

Delete clears the association by setting the polymorphic fields to nil. The values parameter is validated to ensure the provided value matches the current association. Sets the polymorphic ID and type to nil/zero values. Saves the current model to persist the changes.

Example:

post := Post{ID: 5}
err := assoc.Delete(&post)

func (*PolymorphicBelongsTo) Find added in v0.6.0

func (p *PolymorphicBelongsTo) Find(out any, conds ...any) error

Find loads the associated model for a polymorphic belongs-to relationship. The out parameter must be a pointer to a struct for the related model. The conds parameter provides optional WHERE conditions for the query. Uses the polymorphic ID and type to determine which table to query. Infers the table name from the type or model's TableName() method.

Example:

var post Post
err := assoc.Find(&post)

var video Video
err := assoc.Find(&video, "published = ?", true)

func (*PolymorphicBelongsTo) Replace added in v0.6.0

func (p *PolymorphicBelongsTo) Replace(values ...any) error

Replace replaces the current association with the given value. The values parameter must contain exactly one model to associate with. This is equivalent to Append for polymorphic belongs-to relationships.

Example:

video := Video{ID: 10, Title: "My Video"}
err := assoc.Replace(&video)

type PolymorphicHasMany added in v0.6.0

type PolymorphicHasMany struct {
	*Association
	// contains filtered or unexported fields
}

PolymorphicHasMany represents a polymorphic has-many relationship. This allows a model to have many related models that can belong to multiple different model types. Uses polymorphic fields (ID and Type) on the related models to store the relationship.

Example: A Post can have many Comments, and a Video can also have many Comments.

  • comments table has commentable_id and commentable_type columns
  • commentable_id stores the ID of the parent model
  • commentable_type stores the type name (e.g., "Post", "Video")

Database Schema:

posts (id, title, content)
videos (id, title, url)
comments (id, commentable_id, commentable_type, content)

type Post struct {
    ID       uint
    Title    string
    Comments []Comment // polymorphic has-many
}

func NewPolymorphicHasMany added in v0.6.0

func NewPolymorphicHasMany(query contractsorm.Query, model any, association, polymorphicID, polymorphicType, localKey string) *PolymorphicHasMany

NewPolymorphicHasMany creates a new PolymorphicHasMany association. The query parameter provides the query builder for database operations. The model parameter is the model instance that has many related models. The association parameter is the name of the association (e.g., "comments"). The polymorphicID parameter is the polymorphic ID field name on related models (e.g., "commentable_id"). The polymorphicType parameter is the polymorphic type field name on related models (e.g., "commentable_type"). The localKey parameter is the primary key column on the current model (e.g., "id").

Example:

post := Post{ID: 1, Title: "My Post"}
assoc := NewPolymorphicHasMany(db.Query(), &post, "comments", "commentable_id", "commentable_type", "id")

func (*PolymorphicHasMany) Append added in v0.6.0

func (p *PolymorphicHasMany) Append(values ...any) error

Append appends models to the polymorphic association. The values parameter provides the model(s) to append to the association. Sets the polymorphic ID to the current model's local key value. Sets the polymorphic type to the current model's type name. Validates that the value type matches the expected association type. Saves each related model to persist the polymorphic fields.

Example:

comment1 := Comment{Content: "Great post!"}
comment2 := Comment{Content: "Thanks for sharing"}
err := assoc.Append(&comment1, &comment2)

func (*PolymorphicHasMany) Clear added in v0.6.0

func (p *PolymorphicHasMany) Clear() error

Clear clears the association by setting the polymorphic fields to null for all related models. Updates all related models to set polymorphic ID and type to null. Uses a single UPDATE statement for efficiency.

Example:

err := assoc.Clear()

func (*PolymorphicHasMany) Count added in v0.6.0

func (p *PolymorphicHasMany) Count() int64

Count returns the number of records in the association. Counts records where both polymorphic ID and type match the current model.

Example:

count := assoc.Count()

func (*PolymorphicHasMany) Delete added in v0.6.0

func (p *PolymorphicHasMany) Delete(values ...any) error

Delete removes the given values from the association. The values parameter provides the model(s) to remove from the association. Sets the polymorphic fields to null for each related model using direct SQL update. Ensures the model belongs to this association by checking both polymorphic fields. Returns an error if the value was not part of the association.

Example:

comment := Comment{ID: 1}
err := assoc.Delete(&comment)

func (*PolymorphicHasMany) Find added in v0.6.0

func (p *PolymorphicHasMany) Find(out any, conds ...any) error

Find loads the associated models for a polymorphic has-many relationship. The out parameter must be a pointer to a slice for the related models. The conds parameter provides optional WHERE conditions for the query. Uses the local key and model type name to query related models. Filters by both polymorphic ID and polymorphic type.

Example:

var comments []Comment
err := assoc.Find(&comments)

var comments []Comment
err := assoc.Find(&comments, "approved = ?", true)

func (*PolymorphicHasMany) Replace added in v0.6.0

func (p *PolymorphicHasMany) Replace(values ...any) error

Replace replaces the current association with the given values. The values parameter provides the new model(s) for the association. First clears the current association by setting polymorphic fields to null. Then appends the new values.

Example:

comments := []Comment{{Content: "New comment"}, {Content: "Another comment"}}
err := assoc.Replace(comments...)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL