From c842d46b6643f8d4177c77b33a961d33b256d032 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Wed, 6 Nov 2013 22:13:18 +0800 Subject: [PATCH] Add Support for TableName, used to specify struct's table name --- README.md | 15 +++++++++++++++ gorm_test.go | 37 +++++++++++++++++++++++++++++++++++++ model.go | 11 +++++++++++ 3 files changed, 63 insertions(+) diff --git a/README.md b/README.md index 36edc38c..fafc3ff0 100644 --- a/README.md +++ b/README.md @@ -70,9 +70,11 @@ db, err := Open("postgres", "user=gorm dbname=gorm sslmode=disable") // Set the maximum idle database connections db.SetPool(100) + // By default, table name is plural of struct type, if you like singular table name db.SingularTable(true) + // Gorm is goroutines friendly, so you can create a global variable to keep the connection and use it everywhere like this var DB gorm.DB @@ -587,6 +589,19 @@ db.Table("deleted_users").Where("name = ?", "jinzhu").Delete() //// DELETE FROM deleted_users WHERE name = 'jinzhu'; ``` +### Specify Table Name for Struct + +You are possible to specify table name for a struct by defining method TableName + +```go +type Cart struct { +} + +func (c Cart) TableName() string { + return "shopping_cart" +} +``` + ## Run Raw SQl ```go diff --git a/gorm_test.go b/gorm_test.go index d7d62fd1..f6697399 100644 --- a/gorm_test.go +++ b/gorm_test.go @@ -1198,3 +1198,40 @@ func TestRelated(t *testing.T) { t.Errorf("Should get user from credit card correctly") } } + +type Order struct { +} + +type Cart struct { +} + +func (c Cart) TableName() string { + return "shopping_cart" +} + +func TestTableName(t *testing.T) { + var table string + + model := &Model{data: Order{}} + table, _ = model.tableName(false) + if table != "orders" { + t.Errorf("Order table name should be orders") + } + + table, _ = model.tableName(true) + if table != "order" { + t.Errorf("Order's singular table name should be order") + } + + model2 := &Model{data: Cart{}} + table, _ = model2.tableName(false) + if table != "shopping_cart" { + t.Errorf("Cart's singular table name should be shopping_cart") + } + + model3 := &Model{data: &Cart{}} + table, _ = model3.tableName(false) + if table != "shopping_cart" { + t.Errorf("Cart's singular table name should be shopping_cart") + } +} diff --git a/model.go b/model.go index df0b1598..c522734c 100644 --- a/model.go +++ b/model.go @@ -282,6 +282,16 @@ func (m *Model) tableName(singularTableName bool) (str string, err error) { return } + fm := reflect.Indirect(reflect.ValueOf(m.data)).MethodByName("TableName") + if fm.IsValid() { + v := fm.Call([]reflect.Value{}) + if len(v) > 0 { + if result, ok := v[0].Interface().(string); ok { + return result, nil + } + } + } + str = toSnake(m.typeName()) if !singularTableName { @@ -293,6 +303,7 @@ func (m *Model) tableName(singularTableName bool) (str string, err error) { } } } + return }