This repository has been archived on 2022-04-14. You can view files and clone it, but cannot push or open issues or pull requests.
manual-zh-CN/chapter-02/3.tags.md
2020-03-24 09:23:34 +08:00

21 lines
1.3 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

### 使用 Table 和 Tag 改变名称映射
如果所有的命名都是按照 Mapper 的映射来操作的那当然是最理想的。但是如果碰到某个表名或者某个字段名跟映射规则不匹配时我们就需要别的机制来改变。xorm 提供了如下几种方式来进行:
* 如果结构体拥有 `TableName() string` 的成员方法,那么此方法的返回值即是该结构体对应的数据库表名。
* 通过 `engine.Table()` 方法可以改变 struct 对应的数据库表的名称,通过 sturct 中 field 对应的 Tag 中使用 `xorm:"'column_name'"`可以使该 field 对应的 Column 名称为指定名称。这里使用两个单引号将 Column 名称括起来是为了防止名称冲突因为我们在Tag中还可以对这个Column进行更多的定义。如果名称不冲突的情况单引号也可以不使用。
到此名称映射的所有方法都给出了,一共三种方式,这三种是有优先级顺序的。
* 表名的优先级顺序如下:
* `engine.Table()` 指定的临时表名优先级最高
* `TableName() string` 其次
* `Mapper` 自动映射的表名优先级最后
* 字段名的优先级顺序如下:
* 结构体tag指定的字段名优先级较高
* `Mapper` 自动映射的表名优先级较低