不幸的是,使用gorm.Session{DryRun: true}选项并不像使用普通查询那样使调用方可以使用迁移SQL语句。 我现在能看到的唯一方法是通过重新实现gorm.io/gorm/logger.Interface接口来捕获迁移在记录时运行的SQL。具体来说,Trace方法。 type Interface interface { LogMode(LogLevel) Interface Info(context.Context, string, ...interface{}) Warn(context.Context, string, ...interface{}) Error(context.Context, string, ...interface{}) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error)} 在Trace内部,您可以调用fc函数参数来获取SQL和RowsAffected,您可以对其执行任何操作。 For example: import ( "time" "context" "gorm.io/gorm/logger")type RecorderLogger struct { logger.Interface Statements []string}f