📄️ Database Setup
You need to first install the MySQL database (you can also use other databases, but this tutorial uses MySQL as an example). If you're unfamiliar with the installation process, you can search for MySQL tutorials on platforms like Bilibili.
📄️ Database Configuration
Once your database content is ready, you can configure the database in your configuration file by adding the following content:
📄️ Driver Addition and Import
- Initialize MySQL driver import in main.go:
📄️ Database Basic Operations
The Model function in the github.com/gogf/gf/v2/frame/g package returns a gdb.Model object, providing a set of operations for interacting with the database. The Model function accepts a parameter, which is the table name:
📄️ Time Maintenance and Soft Deletion
In practical applications, database tables often include three timestamp fields: creation time, update time, and delete time. GoFrame supports automatic population of these three time fields, which can be of types DATE, DATETIME, or TIMESTAMP.
📄️ Transaction Handling
Conventional Approach
📄️ Using Raw SQL
While the methods provided by Model can handle most data operations, complex scenarios may require custom SQL queries.
📄️ DAO Auto Generation and Usage
Database operations and data structures are typically organized into dao and model. In GoFrame, content for dao and model can be automatically generated. Here are the steps to generate them:
📄️ Field Filtering
When creating or updating data using struct data, especially during updates, some fields may not need updating. Therefore, corresponding fields should not be assigned values. For example:
📄️ Association Query
When querying data involving multiple tables, using joins can be inefficient for large datasets. In GoFrame, model association queries are provided to simplify such operations.