GoLang GORM Embedding Struct from Other Table: A Comprehensive Guide

Abstract: Resolve code duplication by embedding a base struct with common fields like ID and timestamps into multiple GORM models for consistent schema design.

Created: 2026-09-30 by

Embedding structs in GORM allows you to reuse fields across multiple models, simplifying database schema design and query logic. By leveraging Go's anonymous struct embedding, you can automatically map common columns like IDs or timestamps to your primary entities, reducing code duplication while maintaining a clean and maintainable data access layer.

Understanding Struct Embedding in Go

Go provides a powerful feature called struct embedding, which allows one struct to inherit the fields of another. In the context of GORM, this is particularly useful for creating base models that contain common attributes shared by many database tables. For instance, most database records require an ID, a creation timestamp, and an update timestamp. Instead of defining these fields in every single model, you can create a base struct and embed it into your specific domain models.

This approach not only reduces boilerplate code but also ensures consistency across your application's data models. When you define a base struct with GORM tags, those tags are inherited by the embedding struct, allowing GORM to correctly map the embedded fields to database columns. This mechanism is fundamental to building scalable applications where database schemas evolve over time.

Implementing a Base Model

To implement this pattern, start by defining a base struct that contains the common fields. Typically, this includes an ID field and timestamps. Here is how you can define such a base model:

type BaseModel struct {
    ID        uint      `gorm:"primary_key" json:"id"`
    CreatedAt time.Time `json:"created_at"`
    UpdatedAt time.Time `json:"updated_at"`
    DeletedAt gorm.DeletedAt `gorm:"index" json:"deleted_at,omitempty"`
}

In this example, the BaseModel struct includes standard fields used in most relational database tables. The gorm:"primary_key" tag tells GORM that the ID field is the primary key. The CreatedAt and UpdatedAt fields are automatically managed by GORM if configured correctly, and DeletedAt enables soft deletes. By keeping these definitions in a single place, you ensure that any changes to these common fields propagate to all models that embed this base.

Embedding the Base Model in Domain Entities

Once the base model is defined, you can embed it into your specific domain entities. This is done by declaring the base struct as an anonymous field within your new struct. Consider a User model that needs to extend the base functionality:

type User struct {
    BaseModel
    Name     string `gorm:"size:255" json:"name"`
    Email    string `gorm:"uniqueIndex" json:"email"`
    Password string `json:"password"`
}

By embedding BaseModel, the User struct automatically inherits ID, CreatedAt, UpdatedAt, and DeletedAt. You do not need to redefine these fields in the User struct. GORM will treat the embedded fields as if they were part of the User struct itself during database operations. This makes your code cleaner and easier to read, as the specific business logic fields (Name, Email) are distinct from the infrastructure fields.

If you are working with complex relationships, you might find it helpful to look at Simplistic Database: Hundreds of Linguistic Entries - Tech Support for insights on managing large sets of structured data efficiently.

Handling Conflicts and Overrides

While embedding is straightforward, conflicts can arise if both the base struct and the embedding struct define the same field name. In Go, the innermost struct (the one doing the embedding) takes precedence. However, in GORM, this can lead to unexpected behavior if not handled carefully. If you need to override a field definition, you must explicitly redefine it in the embedding struct.

For example, if you want the ID in a specific model to be a string instead of an integer, you cannot simply rely on the embedded BaseModel. You must redefine the ID field in the child struct with the correct type and tags. GORM will then use the definition from the child struct. It is crucial to understand that embedding does not allow for partial overriding of tags; you must provide the full field definition if you wish to change its properties.

Additionally, when dealing with nested embeddings, be cautious of ambiguity. If two embedded structs have fields with the same name, accessing them directly via the parent struct will result in a compilation error. You must qualify the field access using the embedded struct name, e.g., user.BaseModel.ID.

Best Practices for Querying Embedded Fields

When querying data, GORM treats embedded fields as regular fields of the parent struct. This means you can query them directly without any special syntax. For instance, to find users created after a certain date, you can write:

db.Where("created_at > ?", someTime).Find(&users)

This works seamlessly because the created_at field is promoted to the User struct level. However, when joining tables or selecting specific columns, you should be explicit about which fields you are selecting to avoid loading unnecessary data. Using Select can help optimize performance, especially when dealing with large payloads.

Another consideration is serialization. When converting your models to JSON, the embedded fields are included in the output by default. If you want to exclude certain base fields from the API response, you can use the json:"-"` tag in the base struct or override the tag in the child struct. This gives you fine-grained control over what data is exposed to clients.

Frequently Asked Questions

Can I embed multiple structs in GORM?

Yes, Go allows you to embed multiple structs, but you must be careful with field name collisions. If two embedded structs have fields with the same name, you must access them using the struct name qualifier to avoid ambiguity. GORM will still map these fields correctly as long as there are no naming conflicts within the same structural level.

How do I handle auto-increment IDs with embedded structs?

Ensure that the ID field in your base struct has the gorm:"primary_key" tag. GORM automatically handles auto-increment for unsigned integer primary keys. When you embed this base struct, the child struct inherits this behavior, so you do not need to redefine the auto-increment property unless you are changing the key type.

What happens if I modify the base struct later?

Changes to the base struct, such as adding new fields or modifying tags, will automatically apply to all models that embed it. This is a significant advantage for maintaining consistency. However, always run migrations after updating the base struct to ensure the database schema reflects these changes.

Can I use embedded structs for polymorphic associations?

Embedded structs themselves do not dictate association types. You can use embedded structs in conjunction with GORM's polymorphic associations by defining the necessary foreign key and type fields in either the base or child struct. The embedding mechanism is purely for field inheritance and does not interfere with relationship definitions.

Is there a performance penalty for using embedded structs?

No, there is no runtime performance penalty. Struct embedding is a compile-time feature in Go. GORM processes the struct tags at initialization time, so the resulting SQL queries and object mappings are identical to those generated for non-embedded structs. The benefit is primarily in code maintainability and reduced duplication.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More