Question

My database consists of 3 tables (one for storing all items, one for the tags, and one for the relation between the two):

Table: Post Columns: PostID, Name, Desc

Table: Tag Columns: TagID, Name

Table: PostTag Columns: PostID, TagID

What is the best way to save a space separated string (e.g. "smart funny wonderful") into the 3 database tables shown above?

Ultimately I would also need to retrieve the tags and display it as a string again. Thanks!

Was it helpful?

Solution

Roughly, something like this:

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()
        }       
    }

}

OTHER TIPS

If you have a Tag Table, wouldn'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'

In Groovy/Grails, you'd retrieve them as a list, possibly concatenating them into a space separated list for display.

Unless I'm really misunderstanding the question, Groovy/Grails/GORM will handle this with little or no code with the default scaffolding, no real coding required.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top