This repository has been archived on 2022-04-14. You can view files and clone it, but cannot push or open issues or pull requests.
manual-en-US/chapter-04
2020-03-27 14:29:41 +08:00
..
1.created.md Update documents 2020-03-27 14:29:41 +08:00
README.md Update documents 2020-03-27 14:29:41 +08:00

4.Insert data

You can insert objects to database via Insert method.

  • Insert one object
user := new(User)
user.Name = "myname"
affected, err := engine.Insert(user)

After inserted, user.ID will be filled if ID is an autoincremented column.

fmt.Println(user.Id)
  • Insert multiple objects by Slice on one table
users := make([]User, 1)
users[0].Name = "name0"
...
affected, err := engine.Insert(&users)
  • Insert multiple records by Slice of pointer on one table
users := make([]*User, 1)
users[0] = new(User)
users[0].Name = "name0"
...
affected, err := engine.Insert(&users)
  • Insert two objects onto two tables.
user := new(User)
user.Name = "myname"
question := new(Question)
question.Content = "whywhywhwy?"
affected, err := engine.Insert(user, question)
  • Insert multiple objects on multiple tables.
users := make([]User, 1)
users[0].Name = "name0"
...
questions := make([]Question, 1)
questions[0].Content = "whywhywhwy?"
affected, err := engine.Insert(&users, &questions)
  • Insert one or multple objects on multiple tables.
user := new(User)
user.Name = "myname"
...
questions := make([]Question, 1)
questions[0].Content = "whywhywhwy?"
affected, err := engine.Insert(user, &questions)

Notice: If you want to use transaction on inserting, you should use session.Begin() before calling Insert.