github.com/wangyougui/gf/v2@v2.6.5/database/gdb/gdb_z_example_test.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/wangyougui/gf.
     6  
     7  package gdb_test
     8  
     9  import (
    10  	"context"
    11  
    12  	"github.com/wangyougui/gf/v2/database/gdb"
    13  	"github.com/wangyougui/gf/v2/frame/g"
    14  )
    15  
    16  func ExampleTransaction() {
    17  	g.DB().Transaction(context.TODO(), func(ctx context.Context, tx gdb.TX) error {
    18  		// user
    19  		result, err := tx.Insert("user", g.Map{
    20  			"passport": "john",
    21  			"password": "12345678",
    22  			"nickname": "JohnGuo",
    23  		})
    24  		if err != nil {
    25  			return err
    26  		}
    27  		// user_detail
    28  		id, err := result.LastInsertId()
    29  		if err != nil {
    30  			return err
    31  		}
    32  		_, err = tx.Insert("user_detail", g.Map{
    33  			"uid":       id,
    34  			"site":      "https://johng.cn",
    35  			"true_name": "GuoQiang",
    36  		})
    37  		if err != nil {
    38  			return err
    39  		}
    40  		return nil
    41  	})
    42  }