go-gorm / gorm

The fantastic ORM library for Golang, aims to be developer friendly
https://gorm.io
MIT License
37.02k stars 3.94k forks source link

fix: table not change (#6913) #7266

Closed ZiRunHua closed 2 weeks ago

ZiRunHua commented 2 weeks ago

What did this pull request do?

Update Condition for Table Selection: This change allows ParseWithSpecialTableName to re-evaluate and update the table name based on the value passed, not just when the table name is initially empty.

User Case Description

When you use embedded structures, you might write queries like this

type StatisticBase struct {
    Date          time.Time
    Amount, Count int
}

type IncomeStatistic struct {
    StatisticBase
    Tas    int
    UserId uint
}

type ExpendStatistic struct {
    StatisticBase
    UserId uint
}

type Total struct{ Amount, Count int }

type Statistic struct{ Income, Expend Total }

func queryStatistic(db *gorm.DB, start, end time.Time) (result Statistic, err error) {
    query := db.Where("date BETWEEN ? AND ?", start, end)
    query = query.Select("SUM(amount) as Amount,SUM(count) as Count")
    err = query.Model(&IncomeStatistic{}).Scan(&result.Income).Error
    if err != nil {
        return
    }
    err = query.Model(&ExpendStatistic{}).Scan(&result.Expend).Error
    return
}

But the table for the second query did not change.

SELECT SUM(amount) as Amount,SUM(count) as Count FROM `income_statistic` WHERE date BETWEEN '2024-11-03 09:38:53.615' AND '2024-11-08 09:38:53.615';
SELECT SUM(amount) as Amount,SUM(count) as Count FROM `income_statistic` WHERE date BETWEEN '2024-11-03 09:38:53.615' AND '2024-11-08 09:38:53.615';

Since the table is only updated when empty, this is what the "pull request" wants to change, which will give the user more flexibility to manipulate the data as needed.

ZiRunHua commented 2 weeks ago

Oh, the test didn't pass. Maybe it shouldn't be used that way.