Skip to main content
Version: 2.8.x(Latest)

Create Data Table


Create a new data table to store words and add a combined unique index uid, word to restrict a single user from adding the same word multiple times.

CREATE TABLE words (
id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
uid INT UNSIGNED NOT NULL,
word VARCHAR ( 255 ) NOT NULL,
definition TEXT,
example_sentence TEXT,
chinese_translation VARCHAR ( 255 ),
pronunciation VARCHAR ( 255 ),
proficiency_level SMALLINT UNSIGNED,
created_at DATETIME,
updated_at DATETIME
);

ALTER TABLE words ADD UNIQUE (uid, word);
Field NameTypeDescription
idINT UNSIGNEDPrimary key, auto-increment, unique ID for words
uidINT UNSIGNEDUser ID, indicates the owner of the word
wordVARCHAR(255)Word, cannot be null
definitionTEXTWord definition
example_sentenceTEXTExample sentence
chinese_translationVARCHAR(255)Chinese translation of the word
pronunciationVARCHAR(255)Pronunciation of the word
proficiency_levelSMALLINTWord proficiency level, 1 is lowest, 5 is highest
created_atDATETIMERecord creation time
updated_atDATETIMERecord last update time

Generate Word Data Model


$ gf gen dao

After successful execution, the following files will be generated:

internal/model/do/words.go
internal/model/entity/words.go
internal/dao/internal/words.go
internal/dao/words.go

Customize Data Model


Like the user model, replicate the approach in model to customize a data model for use as a Logic input parameter.

internal/model/words.go

package model  

type ProficiencyLevel uint

const (
ProficiencyLevel1 ProficiencyLevel = iota + 1
ProficiencyLevel2
ProficiencyLevel3
ProficiencyLevel4
ProficiencyLevel5
)

type WordInput struct {
Uid uint
Word string
Definition string
ExampleSentence string
ChineseTranslation string
Pronunciation string
ProficiencyLevel ProficiencyLevel
}

Here, we have customized a data type ProficiencyLevel to indicate word proficiency and have defined five enumeration values: ProficiencyLevel1-5 representing the levels from low to high.

This method of using custom types with fixed enumeration values is an advanced programming technique that can be widely applied to various states, such as order status, project stages, etc. Beginners often like to use int across the board, resulting in 1,2,3... numeric states scattered throughout the code, making it less readable and maintainable.