如何使用gorm对数据库进行原始查询并从结果中的不同表中获取字段?

问题描述 投票:0回答:1

我有以下内容(请注意,在查询中我希望从不同的表中获取字段。也许这有某种特殊性):


type Result struct {
    ID        string     `gorm:"column:id"`           
    CreatedAt time.Time  `gorm:"column:created_at"`   
    UpdatedAt time.Time  `gorm:"column:updated_at"`   
    DeletedAt *time.Time `gorm:"column:a_deleted_at"` 
    Category  string     `gorm:"column:category_code"`                    

    LastReleaseID          string    `gorm:"column:r_id"`
    LastReleaseIconID      uuid.UUID `gorm:"column:i_id"`          
    LastReleaseName        string    `gorm:"column:r_name"`
    LastReleaseVersion     string    `gorm:"column:r_version"`
    LastReleaseSubVersion  string    `gorm:"column:r_subversion"`
    LastReleaseStatus      string    `gorm:"column:r_status"`
    
    Developer string  `gorm:"column:b_dev"` 
}





func DoRequestToDB(db *gorm.DB, sqlArgs ...any) error {

    sql := `SELECT
        a."id",
        a."created_at",
        a."updated_at",
        a."deleted_at" AS a_deleted_at,
        a."category_code"
        ,
        r.id AS r_id,
        r.icon_id AS i_id,
        r.name AS r_name,
        r.version AS r_version,
        r.subversion AS r_subVersion
        r.status AS r_status
        ,
        b.developer AS b_dev
    FROM "applications" as a
    JOIN (
        SELECT release_filtered.*
        FROM releases AS release_filtered
        JOIN (
            SELECT
                application_id,
                max(created_at) as max_created_at
            FROM releases
            WHERE deleted_at is null
            AND status in (?)
            GROUP BY "application_id"
        ) AS release_condition
        ON release_filtered.application_id = release_condition.application_id
        AND release_filtered.created_at = release_condition.max_created_at
        and release_filtered.deleted_at is null
    ) AS r
    ON r.application_id = a.id
    JOIN builds AS b
    ON r.build_id = b.id
    WHERE a.deleted_at IS NULL`


    var result := make([]Result, 0)
    err := db.Raw(sqlQuery, sqlArgs...).Find(&result).Error
    if err != nil {
        return nil, err
    }

    return result, nil
}

我使用 PostgreSQL 数据库。我没有收到错误,但结果也没有任何内容。

同时,如果我通过终端中的 psql 实用程序执行相同的查询,我会得到结果。

我做错了什么?

go orm grails-orm go-gorm
1个回答
0
投票

不要使用

Find(&result
函数,而是尝试使用
Rows()
,然后扫描您的值。虽然有点乱,但是可以用。

    var result := make([]Result, 0)
    rows,err := db.Raw(sqlQuery, sqlArgs...).Rows()
    if err != nil {
        return nil, err
    }
    
    for rows.Next() {
        res := new(Result)
        err = r.Scan(&res.ID, &res.CreatedAt, ...) // do this for all your fields
        if err != nil {
            return nil, err
        }
        result = append(result, res)
    }

    return result, nil
© www.soinside.com 2019 - 2024. All rights reserved.