Home  >  Article  >  Backend Development  >  Go language development of door-to-door cooking system: How to implement user consumption recording function?

Go language development of door-to-door cooking system: How to implement user consumption recording function?

WBOY
WBOYOriginal
2023-11-01 17:05:181018browse

Go language development of door-to-door cooking system: How to implement user consumption recording function?

Go language development of door-to-door cooking system: How to implement user consumption recording function?

With the improvement of living standards, people’s demand for food is also getting higher and higher. More and more people are beginning to try to cook by themselves, but many people are unable to do so due to busy work or laziness. Therefore, door-to-door cooking services came into being.

Nowadays, door-to-door cooking services are generally made through online platforms to make reservations and orders. Customers select the dishes and quantities they need through the platform, and after paying the corresponding fee, they can wait for door-to-door service. Among these services, the user consumption record function is particularly important. For service providers, consumption records can help them better manage their accounts, thereby improving operational efficiency; for users, consumption records can check their recent consumption situation to better estimate their consumption ability. .

So, how to implement the user consumption recording function of the door-to-door cooking system? Let’s take a look below.

1. Design the data table

Before thinking about the implementation of the consumption record function, we need to design the corresponding data table first. In this case, we need to design the menu table, order table, order details table and consumption record table.

  • The menu table is designed as follows:
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='菜品表';
  • The order table is designed as follows:
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='订单表';
  • The order details table is designed as follows :
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='订单详情表';
  • The consumption record table is designed as follows:
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='消费记录表';

2. Implementation code

After completing the data table After the design, we need to use Go language to implement the corresponding business logic. The following is the corresponding code:

  • Define structure:
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"`
}
  • Query order details:
// 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
}
  • Add consumption Record:
// 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
}

3. Summary

The above is a case of how to use Go language to implement the user consumption recording function in a simple door-to-door cooking system. Through this case, we can learn how to splice SQL queries, batch queries, traverse query results, and insert data.

Overall, the Go language has the advantages of simplicity, efficiency, and safety, and is loved by the majority of developers. I believe that by reading this case, you can also have a deeper understanding of the Go language. I also hope that it will be helpful to you when implementing the user consumption record function.

The above is the detailed content of Go language development of door-to-door cooking system: How to implement user consumption recording function?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn