When working with GORM for database operations, if you want to set or specify a specific database schema, you can do so by using the Table method during database operations. This is particularly useful when your application needs to handle multiple database schemas or clearly separate different business logic modules within the database.
The following example demonstrates how to specify the database schema when performing database operations with GORM:
gopackage main import ( "gorm.io/driver/postgres" "gorm.io/gorm" ) // Assume we have a User model that we want to store in the "user_management" database schema // Note: The schema is specified via the `Table` method, not the `gorm` tag, as GORM uses this approach for schema management. // ... [rest of the code] ...
In this example, we first define a User struct. Then, in the main function, we initialize the database connection. Notice that when calling AutoMigrate, we explicitly declare the database schema and table name (i.e., user_management.users) using the Table method. This ensures that GORM creates the table in the correct schema. Similarly, when using the Create method to add new User data, it operates within the specified schema.
The benefit of this approach is that it provides high flexibility, allowing developers to precisely control where data should be stored in the database, especially in complex systems where different business data may be separated into different database schemas to improve management efficiency and security.