Home Backend Development Golang 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?

Nov 01, 2023 pm 05:05 PM
go language development Home cooking system

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='菜品表';
Copy after login
  • 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='订单表';
Copy after login
  • 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='订单详情表';
Copy after login
  • 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='消费记录表';
Copy after login

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"`
}
Copy after login
  • 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
}
Copy after login
  • 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
}
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to perform unit testing and integration testing in Go language development How to perform unit testing and integration testing in Go language development Jun 29, 2023 am 11:58 AM

How to perform unit testing and integration testing in Go language development Summary: In software development, unit testing and integration testing are important means to ensure code quality and functional stability. In the Go language, there is also a complete set of tool support, making unit testing and integration testing easier and more efficient. This article will introduce how to perform unit testing and integration testing in Go language development, and demonstrate it through some sample codes. Introduction Go language is an open source programming language that is favored by more and more developers because of its simplicity and powerful features.

How to use Go language to develop the member management function of the ordering system How to use Go language to develop the member management function of the ordering system Nov 01, 2023 am 09:41 AM

How to use Go language to develop the member management function of the ordering system 1. Introduction With the popularity of mobile Internet, the ordering system has become an indispensable part of the catering industry. As an important part of the ordering system, the member management function plays an important role in improving user experience and enhancing user stickiness. This article will introduce how to use Go language to develop the member management function of the ordering system and provide specific code examples. 2. Demand analysis of membership management functions Member registration: Users can register as members through mobile phone number, email, etc. Member login

Go language development work project experience sharing Go language development work project experience sharing Nov 02, 2023 am 09:14 AM

With the development of the Internet, the field of computer science has also ushered in many new programming languages. Among them, Go language has gradually become the first choice of many developers due to its concurrency and concise syntax. As an engineer engaged in software development, I was fortunate to participate in a work project based on the Go language, and accumulated some valuable experience and lessons in the process. First, choosing the right frameworks and libraries is crucial. Before starting the project, we conducted detailed research, tried different frameworks and libraries, and finally chose the Gin framework as our

Go language development tips: Alibaba Cloud interface docking practice sharing Go language development tips: Alibaba Cloud interface docking practice sharing Jul 05, 2023 pm 11:49 PM

Go language development tips: Alibaba Cloud interface docking practice sharing Preface: Nowadays, cloud computing has become one of the core technologies for enterprise information construction, and Alibaba Cloud, as a well-known cloud computing service provider in China, has a wealth of cloud products and service. This article will share some of the author's practical experience in using Go language to connect to Alibaba Cloud interfaces, and explain it in the form of code examples. 1. Introduction of Alibaba Cloud GoSDK Before using the Go language to connect to the Alibaba Cloud interface, we first need to introduce the corresponding Alibaba Cloud GoSDK so that

Advantages and challenges of developing cross-platform applications using Go language Advantages and challenges of developing cross-platform applications using Go language Jul 03, 2023 pm 05:25 PM

Advantages and Challenges of Using Go Language to Develop Cross-Platform Applications With the rapid development of the mobile Internet, cross-platform applications have become an essential skill for developers. As a simple and efficient language with excellent concurrency performance, Go language is gradually favored by developers because of its unique characteristics. This article will explore the advantages and challenges of developing cross-platform applications using the Go language and provide corresponding code examples. 1. Advantages 1. Complete language features: Go language provides a rich standard library, covering various common functions, such as file operations, network communication, etc.

How to develop a simple online education platform using Go language How to develop a simple online education platform using Go language Nov 20, 2023 pm 03:32 PM

How to develop a simple online education platform using Go language Introduction: Today, the development of the Internet has penetrated into all walks of life, and the field of education is no exception. The emergence of online education platforms has made learning more flexible and convenient, and has been favored by students and parents. This article will introduce how to use Go language to develop a simple online education platform, including platform construction, function development and database design. 1. Platform construction First, we need to install the Go language development environment. You can download and install the latest version from the official website

How to optimize network transmission security in Go language development How to optimize network transmission security in Go language development Jun 29, 2023 am 09:41 AM

How to optimize network transmission security in Go language development With the rapid development of the Internet, network transmission security has become more and more important. In Go language development, we can take some measures to optimize the security of network transmission. This article will introduce some common methods and techniques to help you improve the security of Go language network transmission. 1. Use the HTTPS protocol HTTPS is a secure network transmission protocol based on the SSL/TLS protocol. It can provide encryption and authentication functions, and can effectively prevent network transmission from being eavesdropped and

How to use Go language to write the dish inventory management module in the door-to-door cooking system? How to use Go language to write the dish inventory management module in the door-to-door cooking system? Nov 01, 2023 am 09:42 AM

How to use Go language to write the dish inventory management module in the door-to-door cooking system? With the rise of takeout and home cooking, more and more people are choosing to enjoy delicious food at home. As a platform that provides door-to-door cooking services, food inventory management is an integral part. In this article, we will introduce how to use Go language to write the dish inventory management module in the door-to-door cooking system, and provide specific code examples. The functions of the dish inventory management module mainly include adding, querying, modifying and deleting dishes. First, we need to define a dish structure.

See all articles