go 语言 DeletedAt DeletedAt gorm:"index" 时间类型存入字段
时间: 2023-12-06 12:02:04 浏览: 164
在 GORM 中,我们可以通过定义一个 DeletedAt
字段来实现软删除。这个字段的类型通常是 time.Time
,表示被删除的时间。在使用 GORM 进行数据库操作时,当我们调用 Delete
方法删除数据时,GORM 会自动将 DeletedAt
字段设置为当前时间,从而实现软删除的效果。
示例代码:
import "time"
type User struct {
ID uint `gorm:"primaryKey"`
Name string
Age int
DeletedAt time.Time `gorm:"index"`
}
在上面的代码中,我们定义了一个 User
结构体,其中包含一个 DeletedAt
字段,类型为 time.Time
,并添加了 gorm:"index"
标签来为该字段创建索引。
当我们需要软删除某个 User
对象时,只需要调用 Delete
方法即可:
var user User
db.First(&user, 1)
db.Delete(&user)
上面的代码中,我们首先查询 ID 为 1 的 User
对象,并将其赋值给 user
变量,然后调用 Delete
方法删除该对象。此时,GORM 会自动将 DeletedAt
字段设置为当前时间,从而实现软删除的效果。
相关问题
go语言建表 Nid int64 gorm:"primary_key;column:nid" json:"nid" // 系统ID Type string gorm:"type" json:"type" // 消息类型;1文字 LinkId int64 gorm:"link_id" json:"linkId" // 关联ID Uid int64 gorm:"uid" json:"uid" // 用户ID Notice string gorm:"notice" json:"notice" // 通知消息 Kind string gorm:"kind" json:"kind" // 通知种类 UserType string gorm:"user_type" json:"userType" // 用户类型 Status string gorm:"status" json:"status" // 状态;状态0正常9删除 Ctime int64 gorm:"ctime" json:"ctime" // 创建时间详细建表语句
以下是使用 GORM 建表的代码示例:
type Message struct {
Nid int64 `gorm:"primary_key;column:nid" json:"nid"`
Type string `gorm:"type" json:"type"`
LinkId int64 `gorm:"link_id" json:"linkId"`
Uid int64 `gorm:"uid" json:"uid"`
Notice string `gorm:"notice" json:"notice"`
Kind string `gorm:"kind" json:"kind"`
UserType string `gorm:"user_type" json:"userType"`
Status string `gorm:"status" json:"status"`
Ctime int64 `gorm:"ctime" json:"ctime"`
}
// 自动创建名为 messages 的表,如果存在则会自动迁移
db.AutoMigrate(&Message{})
使用上述代码建表,会自动创建一个名为 messages
的表,并且根据结构体字段自动创建相应的列。如果表已经存在,则会自动进行迁移。
用以下字段建表 包含数据库连接Nid int64 gorm:"primary_key;column:nid" json:"nid" // 系统ID Type string gorm:"type" json:"type" // 消息类型;1文字 LinkId int64 gorm:"link_id" json:"linkId" // 关联ID Uid int64 gorm:"uid" json:"uid" // 用户ID Notice string gorm:"notice" json:"notice" // 通知消息 Kind string gorm:"kind" json:"kind" // 通知种类 UserType string gorm:"user_type" json:"userType" // 用户类型 Status string gorm:"status" json:"status" // 状态;状态0正常9删除 Ctime int64 gorm:"ctime" json:"ctime" //
好的,以下是建表的 SQL 语句:
CREATE TABLE IF NOT EXISTS `table_name` (
`nid` bigint(20) NOT NULL COMMENT '系统ID',
`type` varchar(255) DEFAULT NULL COMMENT '消息类型;1文字',
`link_id` bigint(20) DEFAULT NULL COMMENT '关联ID',
`uid` bigint(20) DEFAULT NULL COMMENT '用户ID',
`notice` varchar(255) DEFAULT NULL COMMENT '通知消息',
`kind` varchar(255) DEFAULT NULL COMMENT '通知种类',
`userType` varchar(255) DEFAULT NULL COMMENT '用户类型',
`status` varchar(255) DEFAULT NULL COMMENT '状态;状态0正常9删除',
`ctime` bigint(20) DEFAULT NULL COMMENT '',
PRIMARY KEY (`nid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='表注释';
请将 table_name
替换为你想要的表名,将 表注释
替换为你的表注释。注意,这里使用的是 MySQL 数据库。如果你使用的是其他类型的数据库,语句可能会有所不同。
相关推荐

















