Skip to content
Advertisement

How to Fetch specific number of characters from a string using gorm?

I am using SQLite, if I have a text post or an article that is a 400 character string for example, I want to extract only the first 100 character from it to be used in the front-end.

In line 4 i extracted the latest 5 posts from the db, but i want to limit the body of the post to the first 100 characters only

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
}

How can i do that ?

Advertisement

Answer

What you want is to either use Select or Raw to run the substr sqlite function on the post’s body.

Like this:

err := db.Select("id, title, substr(body, 1, 100) AS body, tags").
    Limit(5).
    Order("created_at DESC").
    Find(&posts).
    Error
// error check

Or with Raw:

err := db.Raw("SELECT id, title, substr(body, 1, 100) AS body, tags FROM posts").
    Scan(&posts).
    Error
// error check

Key aspect to remember is to make sure the column is named body so that scanning into your model works as before.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement