gorm/association.go

256 lines
9.5 KiB
Go
Raw Normal View History

2014-07-30 10:30:21 +04:00
package gorm
2014-07-30 12:22:26 +04:00
import (
"fmt"
"reflect"
)
2016-01-15 17:14:21 +03:00
// Association Association Mode contains some helper methods to handle relationship things easily.
2014-07-30 10:30:21 +04:00
type Association struct {
2015-07-30 12:26:10 +03:00
Scope *Scope
Column string
Error error
Field *Field
2014-07-30 10:30:21 +04:00
}
2016-01-15 17:14:21 +03:00
// Find find out all related associations
2014-07-30 16:48:36 +04:00
func (association *Association) Find(value interface{}) *Association {
association.Scope.related(value, association.Column)
2015-02-13 06:26:02 +03:00
return association.setErr(association.Scope.db.Error)
2014-07-30 16:48:36 +04:00
}
2014-07-30 12:22:26 +04:00
2016-01-15 17:14:21 +03:00
// Append append new associations for many2many, has_many, will replace current association for has_one, belongs_to
2015-12-26 10:19:56 +03:00
func (association *Association) Append(values ...interface{}) *Association {
if relationship := association.Field.Relationship; relationship.Kind == "has_one" {
return association.Replace(values...)
}
return association.saveAssociations(values...)
}
2016-01-15 17:14:21 +03:00
// Replace replace current associations with new one
func (association *Association) Replace(values ...interface{}) *Association {
2015-12-25 17:59:01 +03:00
var (
relationship = association.Field.Relationship
scope = association.Scope
field = association.Field.Field
newDB = scope.NewDB()
)
// Append new values
association.Field.Set(reflect.Zero(association.Field.Field.Type()))
2015-12-26 10:19:56 +03:00
association.saveAssociations(values...)
2015-12-25 15:43:51 +03:00
2015-12-25 17:59:01 +03:00
// Belongs To
2015-12-25 15:43:51 +03:00
if relationship.Kind == "belongs_to" {
2016-01-15 17:14:21 +03:00
// Set foreign key to be null when clearing value (length equals 0)
2015-12-25 17:59:01 +03:00
if len(values) == 0 {
// Set foreign key to be nil
var foreignKeyMap = map[string]interface{}{}
for _, foreignKey := range relationship.ForeignDBNames {
foreignKeyMap[foreignKey] = nil
2015-12-25 15:43:51 +03:00
}
2015-12-25 17:59:01 +03:00
association.setErr(newDB.Model(scope.Value).UpdateColumn(foreignKeyMap).Error)
}
2015-12-25 15:43:51 +03:00
} else {
2016-01-15 17:14:21 +03:00
// Polymorphic Relations
2015-12-26 10:19:56 +03:00
if relationship.PolymorphicDBName != "" {
newDB = newDB.Where(fmt.Sprintf("%v = ?", scope.Quote(relationship.PolymorphicDBName)), scope.TableName())
}
2015-12-25 17:59:01 +03:00
// Relations except new created
if len(values) > 0 {
var associationForeignFieldNames []string
if relationship.Kind == "many_to_many" {
2015-12-25 17:59:01 +03:00
associationForeignFieldNames = relationship.AssociationForeignFieldNames
} else {
2016-01-15 17:14:21 +03:00
associationForeignFieldNames = relationship.AssociationForeignDBNames
2015-12-25 17:59:01 +03:00
}
2016-01-15 17:14:21 +03:00
newPrimaryKeys := association.getPrimaryKeys(associationForeignFieldNames, field.Interface())
if len(newPrimaryKeys) > 0 {
sql := fmt.Sprintf("%v NOT IN (%v)", toQueryCondition(scope, relationship.AssociationForeignDBNames), toQueryMarks(newPrimaryKeys))
newDB = newDB.Where(sql, toQueryValues(newPrimaryKeys)...)
}
2015-12-25 15:43:51 +03:00
}
if relationship.Kind == "many_to_many" {
2016-01-15 17:14:21 +03:00
if sourcePrimaryKeys := association.getPrimaryKeys(relationship.ForeignFieldNames, scope.Value); len(sourcePrimaryKeys) > 0 {
newDB = newDB.Where(fmt.Sprintf("%v IN (%v)", toQueryCondition(scope, relationship.ForeignDBNames), toQueryMarks(sourcePrimaryKeys)), toQueryValues(sourcePrimaryKeys)...)
2016-01-15 17:14:21 +03:00
association.setErr(relationship.JoinTableHandler.Delete(relationship.JoinTableHandler, newDB, relationship))
}
2015-12-25 15:43:51 +03:00
} else if relationship.Kind == "has_one" || relationship.Kind == "has_many" {
var foreignKeyMap = map[string]interface{}{}
for idx, foreignKey := range relationship.ForeignDBNames {
foreignKeyMap[foreignKey] = nil
if field, ok := scope.FieldByName(relationship.AssociationForeignFieldNames[idx]); ok {
newDB = newDB.Where(fmt.Sprintf("%v = ?", scope.Quote(foreignKey)), field.Field.Interface())
}
}
2015-12-25 15:43:51 +03:00
fieldValue := reflect.New(association.Field.Field.Type()).Interface()
2015-12-25 19:23:17 +03:00
association.setErr(newDB.Model(fieldValue).UpdateColumn(foreignKeyMap).Error)
2015-12-25 15:43:51 +03:00
}
}
return association
}
2016-01-15 17:14:21 +03:00
// Delete remove relationship between source & passed arguments, but won't delete those arguments
2015-07-30 12:26:10 +03:00
func (association *Association) Delete(values ...interface{}) *Association {
2015-12-25 19:23:17 +03:00
var (
relationship = association.Field.Relationship
scope = association.Scope
field = association.Field.Field
newDB = scope.NewDB()
)
2014-07-30 18:10:12 +04:00
if len(values) == 0 {
return association
}
2015-12-26 11:06:53 +03:00
var deletingResourcePrimaryFieldNames, deletingResourcePrimaryDBNames []string
for _, field := range scope.New(reflect.New(field.Type()).Interface()).Fields() {
if field.IsPrimaryKey {
deletingResourcePrimaryFieldNames = append(deletingResourcePrimaryFieldNames, field.Name)
deletingResourcePrimaryDBNames = append(deletingResourcePrimaryDBNames, field.DBName)
}
}
deletingPrimaryKeys := association.getPrimaryKeys(deletingResourcePrimaryFieldNames, values...)
2015-07-30 12:26:10 +03:00
if relationship.Kind == "many_to_many" {
2015-12-26 11:06:53 +03:00
// source value's foreign keys
2015-07-30 12:26:10 +03:00
for idx, foreignKey := range relationship.ForeignDBNames {
if field, ok := scope.FieldByName(relationship.ForeignFieldNames[idx]); ok {
2015-12-25 19:23:17 +03:00
newDB = newDB.Where(fmt.Sprintf("%v = ?", scope.Quote(foreignKey)), field.Field.Interface())
2014-07-30 16:48:36 +04:00
}
}
2014-07-30 18:10:12 +04:00
2015-12-26 11:06:53 +03:00
// association value's foreign keys
deletingPrimaryKeys := association.getPrimaryKeys(relationship.AssociationForeignFieldNames, values...)
sql := fmt.Sprintf("%v IN (%v)", toQueryCondition(scope, relationship.AssociationForeignDBNames), toQueryMarks(deletingPrimaryKeys))
newDB = newDB.Where(sql, toQueryValues(deletingPrimaryKeys)...)
2014-07-30 16:48:36 +04:00
2015-12-26 11:06:53 +03:00
association.setErr(relationship.JoinTableHandler.Delete(relationship.JoinTableHandler, newDB, relationship))
2015-07-30 12:26:10 +03:00
} else {
2015-12-25 19:23:17 +03:00
var foreignKeyMap = map[string]interface{}{}
for _, foreignKey := range relationship.ForeignDBNames {
foreignKeyMap[foreignKey] = nil
}
if relationship.Kind == "belongs_to" {
2015-12-25 19:23:17 +03:00
// find with deleting relation's foreign keys
primaryKeys := association.getPrimaryKeys(relationship.AssociationForeignFieldNames, values...)
2015-12-25 19:23:17 +03:00
newDB = newDB.Where(
fmt.Sprintf("%v IN (%v)", toQueryCondition(scope, relationship.ForeignDBNames), toQueryMarks(primaryKeys)),
toQueryValues(primaryKeys)...,
)
2015-12-25 19:23:17 +03:00
// set foreign key to be null
modelValue := reflect.New(scope.GetModelStruct().ModelType).Interface()
if results := newDB.Model(modelValue).UpdateColumn(foreignKeyMap); results.Error == nil {
if results.RowsAffected > 0 {
scope.updatedAttrsWithValues(foreignKeyMap, false)
}
} else {
association.setErr(results.Error)
}
} else if relationship.Kind == "has_one" || relationship.Kind == "has_many" {
2015-12-25 19:23:17 +03:00
// find all relations
primaryKeys := association.getPrimaryKeys(relationship.AssociationForeignFieldNames, scope.Value)
2015-12-25 19:23:17 +03:00
newDB = newDB.Where(
fmt.Sprintf("%v IN (%v)", toQueryCondition(scope, relationship.ForeignDBNames), toQueryMarks(primaryKeys)),
toQueryValues(primaryKeys)...,
)
2015-12-25 19:23:17 +03:00
// only include those deleting relations
newDB = newDB.Where(
2015-12-26 11:06:53 +03:00
fmt.Sprintf("%v IN (%v)", toQueryCondition(scope, deletingResourcePrimaryDBNames), toQueryMarks(deletingPrimaryKeys)),
toQueryValues(deletingPrimaryKeys)...,
2015-12-25 19:23:17 +03:00
)
2015-12-25 19:23:17 +03:00
// set matched relation's foreign key to be null
2015-12-26 09:23:18 +03:00
fieldValue := reflect.New(association.Field.Field.Type()).Interface()
2015-12-26 11:06:53 +03:00
association.setErr(newDB.Model(fieldValue).UpdateColumn(foreignKeyMap).Error)
}
}
// Remove deleted records from field
if association.Error == nil {
if association.Field.Field.Kind() == reflect.Slice {
leftValues := reflect.Zero(association.Field.Field.Type())
for i := 0; i < association.Field.Field.Len(); i++ {
reflectValue := association.Field.Field.Index(i)
primaryKey := association.getPrimaryKeys(deletingResourcePrimaryFieldNames, reflectValue.Interface())[0]
var included = false
for _, pk := range deletingPrimaryKeys {
if equalAsString(primaryKey, pk) {
included = true
}
}
if !included {
leftValues = reflect.Append(leftValues, reflectValue)
}
}
association.Field.Set(leftValues)
} else if association.Field.Field.Kind() == reflect.Struct {
2015-12-26 11:39:08 +03:00
primaryKey := association.getPrimaryKeys(deletingResourcePrimaryFieldNames, association.Field.Field.Interface())[0]
2015-12-26 11:06:53 +03:00
for _, pk := range deletingPrimaryKeys {
if equalAsString(primaryKey, pk) {
association.Field.Set(reflect.Zero(association.Field.Field.Type()))
break
}
}
}
2014-07-30 16:48:36 +04:00
}
2015-12-25 19:23:17 +03:00
2014-07-30 12:22:26 +04:00
return association
2014-07-30 10:30:21 +04:00
}
2016-01-15 17:14:21 +03:00
// Clear remove relationship between source & current associations, won't delete those associations
func (association *Association) Clear() *Association {
2015-12-25 14:33:57 +03:00
return association.Replace()
2014-07-30 10:30:21 +04:00
}
2016-01-15 17:14:21 +03:00
// Count return the count of current associations
2014-07-30 17:43:53 +04:00
func (association *Association) Count() int {
2016-01-12 07:16:22 +03:00
var (
count = 0
relationship = association.Field.Relationship
scope = association.Scope
fieldValue = association.Field.Field.Interface()
newScope = scope.New(fieldValue)
)
2014-07-30 10:30:21 +04:00
2014-07-31 07:08:26 +04:00
if relationship.Kind == "many_to_many" {
2016-01-12 10:27:25 +03:00
relationship.JoinTableHandler.JoinWith(relationship.JoinTableHandler, scope.DB(), association.Scope.Value).Model(fieldValue).Count(&count)
} else if relationship.Kind == "has_many" || relationship.Kind == "has_one" {
2015-07-30 12:26:10 +03:00
query := scope.DB()
for idx, foreignKey := range relationship.ForeignDBNames {
if field, ok := scope.FieldByName(relationship.AssociationForeignDBNames[idx]); ok {
query = query.Where(fmt.Sprintf("%v.%v = ?", newScope.QuotedTableName(), scope.Quote(foreignKey)),
field.Field.Interface())
}
}
2015-02-18 07:30:09 +03:00
if relationship.PolymorphicType != "" {
2015-07-30 12:26:10 +03:00
query = query.Where(fmt.Sprintf("%v.%v = ?", newScope.QuotedTableName(), newScope.Quote(relationship.PolymorphicDBName)), scope.TableName())
}
2016-01-12 07:16:22 +03:00
query.Model(fieldValue).Count(&count)
2014-07-31 07:08:26 +04:00
} else if relationship.Kind == "belongs_to" {
2015-07-30 12:26:10 +03:00
query := scope.DB()
2016-01-12 07:16:22 +03:00
for idx, primaryKey := range relationship.AssociationForeignDBNames {
if field, ok := scope.FieldByName(relationship.ForeignDBNames[idx]); ok {
query = query.Where(fmt.Sprintf("%v.%v = ?", newScope.QuotedTableName(), scope.Quote(primaryKey)),
2015-07-30 12:26:10 +03:00
field.Field.Interface())
}
2014-07-30 17:43:53 +04:00
}
2016-01-12 07:16:22 +03:00
query.Model(fieldValue).Count(&count)
2014-07-30 16:48:36 +04:00
}
2014-07-30 17:43:53 +04:00
return count
2014-07-30 10:30:21 +04:00
}