Ignore association with sql tag

This commit is contained in:
Jinzhu 2014-01-23 08:50:39 +08:00
parent 0459aa89db
commit 2409c26710
3 changed files with 41 additions and 19 deletions

View File

@ -14,6 +14,7 @@ type Field struct {
model *Model
dbName string
isBlank bool
ignoreField bool
isPrimaryKey bool
autoCreateTime bool
autoUpdateTime bool
@ -28,6 +29,14 @@ func (f *Field) parseBlank() {
f.isBlank = isBlank(f.reflectValue)
}
func (f *Field) parseIgnore() {
typ, _, _ := parseSqlTag(f.structField.Tag.Get(f.model.do.db.parent.tagIdentifier))
if typ == "-" {
f.ignoreField = true
}
}
func (f *Field) isScanner() bool {
_, is_scanner := reflect.New(f.reflectValue.Type()).Interface().(sql.Scanner)
return is_scanner

View File

@ -17,6 +17,10 @@ import (
"time"
)
type IgnoredEmbedStruct struct {
Name string
}
type User struct {
Id int64 // Id: Primary key
Birthday time.Time // Time
@ -26,6 +30,7 @@ type User struct {
UpdatedAt time.Time // UpdatedAt: Time of record is updated, will be updated automatically
DeletedAt time.Time // DeletedAt: Time of record is deleted, refer Soft Delete for more
Emails []Email // Embedded structs
IgnoredEmbedStruct IgnoredEmbedStruct `sql:"-"`
BillingAddress Address // Embedded struct
BillingAddressId sql.NullInt64 // Embedded struct's foreign key
ShippingAddress Address // Embedded struct
@ -1249,6 +1254,13 @@ func TestSubStruct(t *testing.T) {
db.Save(&comment3)
}
func TestIgnoreAssociation(t *testing.T) {
user := User{Name: "ignore", IgnoredEmbedStruct: IgnoredEmbedStruct{Name: "IgnoreMe"}}
if err := db.Save(&user).Error; err != nil {
t.Errorf("Should have no error with ignored association, but got ", err)
}
}
func TestRelated(t *testing.T) {
user := User{
Name: "jinzhu",

View File

@ -102,6 +102,7 @@ func (m *Model) fields(operation string) (fields []*Field) {
field.Value = value.Interface()
field.parseAssociation()
field.parseBlank()
field.parseIgnore()
c <- &field
}(field_struct, c)
}
@ -271,7 +272,7 @@ func (m *Model) setValueByColumn(name string, value interface{}, out interface{}
func (m *Model) beforeAssociations() (fields []*Field) {
for _, field := range m.fields("null") {
if field.beforeAssociation && !field.isBlank {
if field.beforeAssociation && !field.isBlank && !field.ignoreField {
fields = append(fields, field)
}
}
@ -280,7 +281,7 @@ func (m *Model) beforeAssociations() (fields []*Field) {
func (m *Model) afterAssociations() (fields []*Field) {
for _, field := range m.fields("null") {
if field.afterAssociation && !field.isBlank {
if field.afterAssociation && !field.isBlank && !field.ignoreField {
fields = append(fields, field)
}
}