---
title: "4.5.单词分页列表"
url: "https://goframe.org/course/starbook/word-list"
markdown_url: "https://goframe.org/course/starbook/word-list.md"
locale: "zh-Hans"
version: "2.10.x(Latest)"
section: "实战教程"
category: "实战教程 / starbook / 第四章-单词管理"
published: "2024-11-16"
updated: "2025-03-17"
description: "使用GET方式查询单词的分页列表，包含模糊查询功能。定义结构体保存单词字段，包括id、单词、定义及熟练度。在GoFrame框架中编写Logic，用于处理数据的查询和分页操作。通过Controller调用Logic，实现数据的获取和返回，支持综合的接口测试。"
keywords: ["GoFrame", "单词查询", "API分页", "模糊查询", "数据结构", "单词列表", "接口测试", "GoFrame框架", "API请求", "数据处理"]
---

# 4.5.单词分页列表

查询单词分页列表使用`GET`方式，并且提供一些入参：

| 字段名  | 类型       | json          | valid           | 描述        |
| ---- | -------- | ------------- | --------------- | --------- |
| Word | `string` | `json:"word"` | `length:1,100`  | 模糊查询单词    |
| Page | `int`    | `json:"page"` | `min:1`         | 页码，默认1    |
| Size | `int`    | `json:"size"` | `between:1,100` | 每页数量，默认10 |
## 添加Api
---
定义一个结构体`List`保存一个单词的字段。在`ListRes`中返回一个`List`切片，表示单词列表，`Total`表示所有单词数量，返回给前端方便做分页操作。

*api/words/v1/words.go*
```go
...

type List struct {
    Id               uint                   `json:"id"`
    Word             string                 `json:"word"`
    Definition       string                 `json:"definition"`
    ProficiencyLevel model.ProficiencyLevel `json:"proficiencyLevel"`
}

type ListReq struct {  
    g.Meta `path:"words" method:"get" sm:"列表" tags:"单词"`  
    Word   string `json:"word" v:"length:1,100" dc:"模糊查询单词"`  
    Page   int    `json:"page" v:"min:1" dc:"页码，默认1"`  
    Size   int    `json:"size" v:"between:1,100" dc:"每页数量，默认10"`  
}  
  
type ListRes struct {  
    List  []List `json:"list"`  
    Total uint   `json:"total"`  
}
```

## 编写Logic
---
*internal/logic/words/words.go*
```go
...

type ListInput struct {  
    Uid  uint  
    Word string  
    Page int  
    Size int  
}  
  
func (w *Words) List(ctx context.Context, in ListInput) (list []entity.Words, total int, err error) {  
    // 对于查询初始值的处理  
    if in.Page == 0 {  
       in.Page = 1  
    }  
    if in.Size == 0 {  
       in.Size = 15  
    }  
  
    var (  
       cls = dao.Words.Columns()  
       orm = dao.Words.Ctx(ctx)  
    )  
    // 组成查询链  
    if in.Uid > 0 {  
       orm = orm.Where(cls.Uid, in.Uid)  
    }  
  
    // 模糊查询  
    if len(in.Word) != 0 {  
       orm = orm.WhereLike(cls.Word, "%"+in.Word+"%")  
    }  
    orm = orm.OrderDesc(cls.CreatedAt).OrderDesc(cls.Id).Page(in.Page, in.Size)  
    if err = orm.ScanAndCount(&list, &total, true); err != nil {  
       return  
    }  
    return  
}
```

上述代码用到了`orm.WhereLike(cls.Word, "%"+in.Word+"%")`，它是模糊查询的意思，最终会生成`word LIKE '%{word}%'` 子句。

`AllAndCount`用于同时查询数据记录列表及总数量，一般用于分页查询场景中，简化分页查询逻辑。

## Controller调用Logic
---
*internal/controller/words/words_v1_list.go*
```go
package words  
  
import (  
    "context"  
  
    "star/api/words/v1"
    "star/internal/logic/words"
)  
  
func (c *ControllerV1) List(ctx context.Context, req *v1.ListReq) (res *v1.ListRes, err error) {  
    uid, err := c.users.GetUid(ctx)  
    if err != nil {  
        return nil, err  
    }  
    wordList, total, err := c.words.List(ctx, words.ListInput{  
        Uid:  uid,  
        Word: req.Word,  
        Page: req.Page,  
        Size: req.Size,  
    })  
    if err != nil {  
        return nil, err  
    }  
  
    var list []v1.List  
    for _, v := range wordList {  
        list = append(list, v1.List{  
            Id:               v.Id,  
            Word:             v.Word,  
            Definition:       v.Definition,  
            ProficiencyLevel: v1.ProficiencyLevel(v.ProficiencyLevel),  
        })  
    }  
  
    return &v1.ListRes{  
        List:  list,  
        Total: uint(total),  
    }, nil  
}
```

## 接口测试
---
```bash
$ curl -X GET http://127.0.0.1:8000/v1/words \
     -H "Authorization: eyJhbGci...5U" \
     -H "Content-Type: application/json" \

{
    "code": 0,
    "message": "",
    "data": {
        "list": [
            {
                "id": 1,
                "word": "example_update",
                "definition": "A representative form or pattern.",
                "proficiencyLevel": 3
            }
        ],
        "total": 1
    }
}
```
