Initialize new model - Sharykhin/go-modular GitHub Wiki
The models are responsible for working with database and in most cases they represent tables.
To create model go to application/model or application/modules/modulename/model and create a new folder which will be called as you model, e.g. todo into this directory create file of you model, e.g. todo.go
So, let's look at an example of a ready model:
package todo
import "go-modular/core/database"
type Todo struct {
database.Model
todoid int
title string
isdone bool "false"
}
func New() (*Todo) {
todo := new(Todo)
todo.Schema = map[string]interface{}{
"todoid":nil,
"title":nil,
"isdone":false,
}
todo.PrimaryKey="todoid"
todo.TableName="todo"
return todo
}
func (todo *Todo) SetTitle(title string) {
todo.Schema["title"] = title
}
func (todo *Todo) SetIsDone(isdone bool) {
todo.Schema["isdone"] = isdone
}
func (todo *Todo) GetTitle() (interface{}) {
return todo.Schema["title"]
}
func (todo *Todo) GetIsDone() (interface{}) {
return todo.Schema["isdone"]
}
func (todo *Todo) GetId() (interface{}) {
return todo.Schema[todo.PrimaryKey]
}
First of all you have to specify your package
then you initialize new struct which will include database.Model:
type Todo struct {
database.Model
todoid int
title string
isdone bool "false"
}
The fields after database.Model represent structure of table. Then it's required to create method New
func New() (*Todo) {
todo := new(Todo)
todo.Schema = map[string]interface{}{
"todoid":nil,
"title":nil,
"isdone":false,
}
todo.PrimaryKey="todoid"
todo.TableName="todo"
return todo
}
This method return Todo instance We have to initialize Shema, field of primary key and table name, all of this steps are required. As you can notice we specified the same fields in Schema as for model. You should pay attention that fields in Schema are more important such as they take part in all methods such as Save, Delete
The we have to specify getters and setters to make possibility working with our model
func (todo *Todo) SetTitle(title string) {
todo.Schema["title"] = title
}
func (todo *Todo) GetTitle() (interface{}) {
return todo.Schema["title"]
}