---
title: "4.4.编辑单词"
url: "https://goframe.org/course/starbook/word-update"
markdown_url: "https://goframe.org/course/starbook/word-update.md"
locale: "zh-Hans"
version: "2.10.x(Latest)"
section: "实战教程"
category: "实战教程 / starbook / 第四章-单词管理"
published: "2024-11-16"
updated: "2025-05-14"
description: "利用GoFrame框架中的REST API来更新单词信息，包括单词的定义、例句、中文翻译及发音等。强调了在编辑操作中的唯一性检查和权限验证逻辑，并通过代码示例展示了如何使用数据库进行数据更新及错误处理。"
keywords: ["GoFrame", "单词更新", "REST API", "PUT请求", "单词定义", "唯一性检查", "更新逻辑", "权限验证", "数据库操作", "错误处理"]
---

# 4.4.编辑单词

编辑单词使用`PUT`方式，代表更新资源。
## 添加 Api
---
*api/words/v1/words.go*
```go
type UpdateReq struct {  
    g.Meta             `path:"words/{id}" method:"put" sm:"更新" tags:"单词"`  
    Id                 uint             `json:"id" v:"required"`  
    Word               string           `json:"word" v:"required|length:1,100" dc:"单词"`  
    Definition         string           `json:"definition" v:"required|length:1,300" dc:"单词定义"`  
    ExampleSentence    string           `json:"example_sentence" v:"required|length:1,300" dc:"例句"`  
    ChineseTranslation string           `json:"chinese_translation" v:"required|length:1,300" dc:"中文翻译"`  
    Pronunciation      string           `json:"pronunciation" v:"required|length:1,100" dc:"发音"`  
    ProficiencyLevel   ProficiencyLevel `json:"proficiency_level" v:"required|between:1,5" dc:"熟练度，1最低，5最高"`  
}  
  
type UpdateRes struct {  
}
```

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

...

type UpdateInput struct {  
    Uid                uint  
    Word               string  
    Definition         string  
    ExampleSentence    string  
    ChineseTranslation string  
    Pronunciation      string  
    ProficiencyLevel   v1.ProficiencyLevel  
}  
  
func (w *Words) Update(ctx context.Context, id uint, in UpdateInput) error {  
    var cls = dao.Words.Columns()  
  
    count, err := dao.Words.Ctx(ctx).  
       Where(cls.Uid, in.Uid).  
       Where(cls.Word, in.Word).  
       WhereNot(cls.Id, id).  
       Count()  
    if err != nil {  
       return err  
    }  
    if count > 0 {  
       return gerror.New("单词已存在")  
    }  
  
    _, err = dao.Words.Ctx(ctx).Data(do.Words{  
       Word:               in.Word,  
       Definition:         in.Definition,  
       ExampleSentence:    in.ExampleSentence,  
       ChineseTranslation: in.ChineseTranslation,  
       Pronunciation:      in.Pronunciation,  
       ProficiencyLevel:   in.ProficiencyLevel,  
    }).Where(cls.Id, id).Where(cls.Uid, in.Uid).Update()  
    if err != nil {  
       return err  
    }  
    return nil  
}

...
```

必须在`ORM`链式中加上`Uid`判断条件，以防止越权，后续的查询，删除动作同样如此。另外加上`WhereNot`，以忽略自身的单词重复检测。

## Controller调用Logic
---
*internal/controller/words/words_v1_update.go*
```go
package words  
  
import (  
    "context"  
  
    "star/api/words/v1"
    "star/internal/logic/words"
)  
  
func (c *ControllerV1) Update(ctx context.Context, req *v1.UpdateReq) (res *v1.UpdateRes, err error) {
    uid, err := c.users.GetUid(ctx)
	if err != nil {
		return nil, err
	}
    err = c.words.Update(ctx, req.Id, words.UpdateInput{
        Uid:                uid,
        Word:               req.Word,  
        Definition:         req.Definition,  
        ExampleSentence:    req.ExampleSentence,  
        ChineseTranslation: req.ChineseTranslation,  
        Pronunciation:      req.Pronunciation,  
        ProficiencyLevel:   req.ProficiencyLevel,  
    })  
    return nil, err  
}
```

## 接口测试
---
```bash
$ curl -X PUT http://127.0.0.1:8000/v1/words/1 \
     -H "Authorization: eyJhbGci...5U" \
     -H "Content-Type: application/json" \
     -d '{
           "word": "example_update",
           "definition": "A representative form or pattern.",
           "example_sentence": "This is an example sentence.",
           "chinese_translation": "例子2",
           "pronunciation": "ɪɡˈzɑːmp(ə)l",
           "proficiency_level": 3
         }'

{
    "code": 0,
    "message": "",
    "data": null
}
```
执行命令，查询数据是否正常更新：
```sql
$ SELECT * FROM words;
```
  
| id  | uid | word           | definition                        | example_sentence             | chinese_translation | pronunciation | proficiency_level | created_at          | updated_at          |
| --- | --- | -------------- | --------------------------------- | ---------------------------- | ------------------- | ------------- | ----------------- | ------------------- | ------------------- |
| 1   | 1   | example_update | A representative form or pattern. | This is an example sentence. | 例子2                  | ɪɡˈzɑːmp(ə)l  | 3                 | 2024/11/12 15:38:50 | 2024/11/12 15:48:50 |
