搜尋
首頁後端開發Golang上門做菜系統的Go語言開發:如何實現使用者消費記錄功能?

上門做菜系統的Go語言開發:如何實現使用者消費記錄功能?

上門做菜系統的Go語言開發:如何實現使用者消費記錄功能?

隨著生活水準的提高,人們對飲食的需求也越來越高。越來越多的人開始嘗試自己動手做飯,然而也有不少人因為工作繁忙或懶惰心態無法實現。因此,上門做菜服務應運而生。

而現在的到府做菜服務,一般都是透過網路平台預約下單。顧客透過平台選擇需要的菜色和數量,支付相應的費用後,便可等待上門服務。而在這些服務中,使用者消費記錄功能顯得格外重要。對於服務提供者來講,消費記錄可以幫助他們更好的管理帳務,從而提高營運效率;對於用戶來講,消費記錄可以查看自己近期的消費情況,以便於更好的預估自己的消費能力。

那麼,如何實現上門做菜系統的使用者消費記錄功能呢?下面我們來一起看看。

一、設計資料表

在思考消費記錄功能的實作之前,我們需要先設計對應的資料表。在這個案例中,我們需要設計菜色表、訂單表、訂單詳情表以及消費記錄表。

  • 菜色表設計如下:
CREATE TABLE IF NOT EXISTS `dishes` (
    `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '菜品 ID',
    `name` VARCHAR(50) NOT NULL COMMENT '菜名',
    `image` VARCHAR(100) NOT NULL COMMENT '图片地址',
    `category_id` INT(10) UNSIGNED NOT NULL COMMENT '分类 ID',
    `price` FLOAT(10,2) UNSIGNED NOT NULL COMMENT '价格',
    `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    PRIMARY KEY (`id`)
) ENGINE=InnoDB CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='菜品表';
  • 訂單表設計如下:
CREATE TABLE IF NOT EXISTS `orders` (
    `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '订单 ID',
    `user_id` INT(10) UNSIGNED NOT NULL COMMENT '用户 ID',
    `total_price` FLOAT(10,2) UNSIGNED NOT NULL COMMENT '订单总价',
    `status` TINYINT(1) UNSIGNED NOT NULL DEFAULT '0' COMMENT '订单状态,0:未支付,1:已支付,2:已完成,3:已取消',
    `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    PRIMARY KEY (`id`)
) ENGINE=InnoDB CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='订单表';
  • 訂單詳情表設計如下:
CREATE TABLE IF NOT EXISTS `order_items` (
    `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '订单详情 ID',
    `order_id` INT(10) UNSIGNED NOT NULL COMMENT '订单 ID',
    `dish_id` INT(10) UNSIGNED NOT NULL COMMENT '菜品 ID',
    `quantity` SMALLINT(5) UNSIGNED NOT NULL COMMENT '数量',
    `price` FLOAT(10,2) UNSIGNED NOT NULL COMMENT '单价',
    `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    PRIMARY KEY (`id`)
) ENGINE=InnoDB CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='订单详情表';
  • 消費記錄表設計如下:
CREATE TABLE IF NOT EXISTS `consumption_records` (
    `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '消费记录 ID',
    `user_id` INT(10) UNSIGNED NOT NULL COMMENT '用户 ID',
    `order_id` INT(10) UNSIGNED NOT NULL COMMENT '订单 ID',
    `money` FLOAT(10,2) UNSIGNED NOT NULL COMMENT '消费金额',
    `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    PRIMARY KEY (`id`)
) ENGINE=InnoDB CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='消费记录表';

二、實作代碼

在完成資料表的設計後,我們需要使用Go 語言來實現對應的業務邏輯。以下是對應程式碼:

  • 定義結構體:
type ConsumptionRecord struct {
    ID        uint32    `db:"id" json:"id"`
    UserID    uint32    `db:"user_id" json:"user_id"`
    OrderID   uint32    `db:"order_id" json:"order_id"`
    Money     float32   `db:"money" json:"money"`
    CreatedAt time.Time `db:"created_at" json:"created_at"`
    UpdatedAt time.Time `db:"updated_at" json:"updated_at"`
}

type OrderDetail struct {
    ID         uint32    `db:"id" json:"id"`
    OrderID    uint32    `db:"order_id" json:"order_id"`
    DishID     uint32    `db:"dish_id" json:"dish_id"`
    Quantity   uint16    `db:"quantity" json:"quantity"`
    Price      float32   `db:"price" json:"price"`
    CreatedAt  time.Time `db:"created_at" json:"created_at"`
    UpdatedAt  time.Time `db:"updated_at" json:"updated_at"`
    Dish       *Dish     `db:"-" json:"dish"`
}

type Order struct {
    ID         uint32         `db:"id" json:"id"`
    UserID     uint32         `db:"user_id" json:"user_id"`
    TotalPrice float32        `db:"total_price" json:"total_price"`
    Status     OrderStatus    `db:"status" json:"status"`
    CreatedAt  time.Time      `db:"created_at" json:"created_at"`
    UpdatedAt  time.Time      `db:"updated_at" json:"updated_at"`
    Items      []*OrderDetail `db:"-" json:"items"`
}
  • #查詢訂單詳情:
// GetOrderDetailsByOrderIDs 根据订单 ID 列表查询订单详情
func GetOrderDetailsByOrderIDs(DB *sql.DB, orderIDs []uint32) ([]*OrderDetail, error) {
    details := make([]*OrderDetail, 0)

    if len(orderIDs) == 0 {
        return details, nil
    }

    // 拼接查询 SQL
    var placeHolders strings.Builder
    var args []interface{}
    for i, id := range orderIDs {
        if i != 0 {
            placeHolders.WriteString(", ")
        }
        placeHolders.WriteString("?")
        args = append(args, id)
    }

    query := fmt.Sprintf(`
        SELECT
            id, order_id, dish_id, quantity, price, created_at, updated_at
        FROM
            order_items
        WHERE
            order_id IN (%s)
    `, placeHolders.String())

    rows, err := DB.Query(query, args...)
    if err != nil {
        return nil, err
    }
    defer rows.Close()

    // 遍历查询结果,并填充菜品信息到订单详情结构体
    for rows.Next() {
        detail := &OrderDetail{}
        err := rows.Scan(
            &detail.ID, &detail.OrderID, &detail.DishID, &detail.Quantity,
            &detail.Price, &detail.CreatedAt, &detail.UpdatedAt)
        if err != nil {
            return nil, err
        }

        dish, err := GetDishByID(DB, detail.DishID)
        if err != nil {
            return nil, err
        }
        detail.Dish = dish

        details = append(details, detail)
    }

    return details, nil
}
  • 新增消費記錄:
// AddConsumptionRecord 添加消费记录
func AddConsumptionRecord(
    DB *sql.DB,
    userID uint32,
    orderID uint32,
    money float32) error {

    insertQuery := `
        INSERT INTO consumption_records (user_id, order_id, money)
        VALUES (?, ?, ?)
    `
    _, err := DB.Exec(insertQuery, userID, orderID, money)
    if err != nil {
        return err
    }

    return nil
}

三、總結

上面是一個簡單的上門做菜系統中,如何使用Go 語言實作使用者消費記錄功能的案例。透過這個案例,我們可以學習拼接查詢 SQL 的方法、批次查詢的方法、遍歷查詢結果的方法以及插入資料的方法。

整體來看,Go 語言具有簡單、高效、安全等優點,並得到了廣大開發人員的喜愛。相信透過閱讀這個案例,你也能對 Go 語言有更深的了解,同時也希望能夠對你在實現使用者消費記錄功能時有所幫助。

以上是上門做菜系統的Go語言開發:如何實現使用者消費記錄功能?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
使用GO編程語言構建可擴展系統使用GO編程語言構建可擴展系統Apr 25, 2025 am 12:19 AM

goisidealforbuildingscalablesystemsduetoitssimplicity,效率和建築物內currencysupport.1)go'scleansyntaxandaxandaxandaxandMinimalisticDesignenhanceProductivityAndRedCoductivityAndRedCuceErr.2)ItSgoroutinesAndInesAndInesAndInesAndineSandChannelsEnablenableNablenableNableNablenableFifficConcurrentscorncurrentprogragrammentworking torkermenticmminging

有效地使用Init功能的最佳實踐有效地使用Init功能的最佳實踐Apr 25, 2025 am 12:18 AM

Initfunctionsingorunautomationbeforemain()andareusefulforsettingupenvorments和InitializingVariables.usethemforsimpletasks,避免使用輔助效果,andbecautiouswithTestingTestingTestingAndLoggingTomaintAnainCodeCodeCodeClarityAndTestesto。

INIT函數在GO軟件包中的執行順序INIT函數在GO軟件包中的執行順序Apr 25, 2025 am 12:14 AM

goinitializespackagesintheordertheordertheyimported,thenexecutesInitFunctionswithinApcageIntheirdeFinityOrder,andfilenamesdetermineTheOrderAcractacractacrosmultiplefiles.thisprocessCanbeCanbeinepessCanbeInfleccessByendercrededBydeccredByDependenciesbetenciesbetencemendencenciesbetnependendpackages,whermayleLeadtocomplexinitialitialializizesizization

在GO中定義和使用自定義接口在GO中定義和使用自定義接口Apr 25, 2025 am 12:09 AM

CustomInterfacesingoarecrucialforwritingFlexible,可維護,andTestableCode.TheyEnableDevelostOverostOcusonBehaviorBeiroveration,增強ModularityAndRobustness.byDefiningMethodSigntulSignatulSigntulSignTypaterSignTyperesthattypesmustemmustemmustemmustemplement,InterfaceSallowForCodeRepodEreusaperia

在GO中使用接口進行模擬和測試在GO中使用接口進行模擬和測試Apr 25, 2025 am 12:07 AM

使用接口進行模擬和測試的原因是:接口允許定義合同而不指定實現方式,使得測試更加隔離和易於維護。 1)接口的隱式實現使創建模擬對像變得簡單,這些對像在測試中可以替代真實實現。 2)使用接口可以輕鬆地在單元測試中替換服務的真實實現,降低測試複雜性和時間。 3)接口提供的靈活性使得可以為不同測試用例更改模擬行為。 4)接口有助於從一開始就設計可測試的代碼,提高代碼的模塊化和可維護性。

在GO中使用init進行包裝初始化在GO中使用init進行包裝初始化Apr 24, 2025 pm 06:25 PM

在Go中,init函數用於包初始化。 1)init函數在包初始化時自動調用,適用於初始化全局變量、設置連接和加載配置文件。 2)可以有多個init函數,按文件順序執行。 3)使用時需考慮執行順序、測試難度和性能影響。 4)建議減少副作用、使用依賴注入和延遲初始化以優化init函數的使用。

GO的選擇語句:多路復用並發操作GO的選擇語句:多路復用並發操作Apr 24, 2025 pm 05:21 PM

go'SselectStatementTreamLinesConcurrentProgrambyMultiplexingOperations.1)itallowSwaitingOnMultipleChannEloperations,執行thefirstreadyone.2)theDefirstreadyone.2)thedefefcasepreventlocksbysbysbysbysbysbythoplocktrograpraproxrograpraprocrecrecectefnoopeready.3)

GO中的高級並發技術:上下文和候補組GO中的高級並發技術:上下文和候補組Apr 24, 2025 pm 05:09 PM

contextancandwaitgroupsarecrucialingoformanaginggoroutineseflect.1)context contextsallowsAllowsAllowsAllowsAllowsAllingCancellationAndDeadLinesAcrossapibiboundaries,確保GoroutinesCanbestoppedGrace.2)WaitGroupsSynChronizeGoroutines,確保Allimizegoroutines,確保AllizeNizeGoROutines,確保AllimizeGoroutines

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具