How to parse, save and retrieve a string with tags separated by spaces?

My database consists of 3 tables (one for storing all elements, one for tags and one for the relationship between them):

Table: Message Columns: PostID, Name, Desc

Table: Tag Columns: TagID, Name

Table: PostTag Columns: PostID, TagID

What is the best way to keep a row separated by space (for example, "smart funny wonderful") in the 3 table tables shown above?

Ultimately, I will also need to get the tags and display them again as a string. Thank!

+3
source share
2 answers

Like that:

class Post {
    static hasMany [tags:Tag]
}

class Tag {
    static belongsTo = Post
    static hasMany [posts:Post]
}

class someService {

    def createPostWithTags(name, desc, tags) {      
        def post = new Post(name: name, desc: desc).save()
        tags.split(' ').each { tagName ->
            def tag = Tag.findByName(tag) ?: new Tag(name: tagName)
            post.addToTags(tag).save()
        }       
    }

}
+4
source

If you have a tag table, don't you have a row for each tag?

tag.id = 1; tag.name = 'smart'
tag.id = 2; tag.name = 'funny'
tag.id = 3; tag.name = 'wonderful'

Groovy/Grails , , , .

, Groovy/Grails/GORM , .

+1

Source: https://habr.com/ru/post/1698842/


All Articles