如何使用 gorm 从字符串中获取特定数量的字符?
How to Fetch specific number of characters from a string using gorm?
我正在使用 SQLite,例如,如果我有一个文本 post 或一篇 400 个字符的文章,我只想从中提取前 100 个字符以用于前面-结束。
在第 4 行中,我从数据库中提取了最新的 5 个 post,但我想将 post 的正文限制为仅前 100 个字符
func GetLatestPosts() *[]Post {
db := database.Connect()
var posts []Post
db.Limit(5).Order("created_at desc").Find(&posts)
// SELECT LEFT(body, 100) FROM posts
// db.Raw("SELECT id, title, body, tags FROM posts").Scan(&posts)
return &posts
}
我该怎么做?
你想要的是使用 Select
或 Raw
到 运行 post 主体上的 substr
sqlite 函数。
像这样:
err := db.Select("id, title, substr(body, 1, 100) AS body, tags").
Limit(5).
Order("created_at DESC").
Find(&posts).
Error
// error check
或原始:
err := db.Raw("SELECT id, title, substr(body, 1, 100) AS body, tags FROM posts").
Scan(&posts).
Error
// error check
要记住的关键方面是确保列已命名 body
以便扫描到您的模型时像以前一样工作。
我正在使用 SQLite,例如,如果我有一个文本 post 或一篇 400 个字符的文章,我只想从中提取前 100 个字符以用于前面-结束。
在第 4 行中,我从数据库中提取了最新的 5 个 post,但我想将 post 的正文限制为仅前 100 个字符
func GetLatestPosts() *[]Post {
db := database.Connect()
var posts []Post
db.Limit(5).Order("created_at desc").Find(&posts)
// SELECT LEFT(body, 100) FROM posts
// db.Raw("SELECT id, title, body, tags FROM posts").Scan(&posts)
return &posts
}
我该怎么做?
你想要的是使用 Select
或 Raw
到 运行 post 主体上的 substr
sqlite 函数。
像这样:
err := db.Select("id, title, substr(body, 1, 100) AS body, tags").
Limit(5).
Order("created_at DESC").
Find(&posts).
Error
// error check
或原始:
err := db.Raw("SELECT id, title, substr(body, 1, 100) AS body, tags FROM posts").
Scan(&posts).
Error
// error check
要记住的关键方面是确保列已命名 body
以便扫描到您的模型时像以前一样工作。