Return to Snippet

Revision: 4477
at December 19, 2007 14:34 by dima767


Updated Code
def setup = {
    new User(name:'user1').save(flush:true)
    new User(name:'user2').save(flush:true)

    tagsForUser1 = ['tag1','tag2']
    tagsForUser2 = ['tag1']

    u1 = User.findByName('user1')
    u2 = User.findByName('user2')
    
    //ITEM1 ***************************************************
    item1 = new Taggable(name:'item1')
    item1.user = u1
    tagsForUser1.each {
        t = Tag.findByName(it)
        if(!t) {
            t = new Tag(name:it).save()
        }
        item1.addToTags(new Tagging(user:u1,tag:t,taggable:item1))
    }
    item1.save(flush:true)
    
    //ITEM2 **************************************************
    item2 = new Taggable(name:'item2')
    item2.user = u2
    tagsForUser2.each {
        t = Tag.findByName(it)
        if(!t) {
            t = new Tag(name:it).save()
        }
        item2.addToTags(new Tagging(user:u2,tag:t,taggable:item2))
    }
    item2.save(flush:true)
}

//setup()

t = Tag.findByName('tag1')
itemsForUserAndTag = Taggable.withCriteria {
    and {
        eq('user', u2)
        tags {
            eq('tag', t)
        }
    }
}

itemsForTag = Taggable.withCriteria {
    tags {
        eq('tag', t)
    }
}

println "Items for user and tag: $itemsForUserAndTag.name"
println "Items for tag: $itemsForTag.name"

Revision: 4476
at December 19, 2007 13:44 by dima767


Initial Code
def setup = {
    new User(name:'user1').save(flush:true)
    new User(name:'user2').save(flush:true)

    tagsForUser1 = ['tag1','tag2']
    tagsForUser2 = ['tag1']

    u1 = User.findByName('user1')
    u2 = User.findByName('user2')
    
    //ITEM1 ***************************************************
    item1 = new Taggable(name:'item1')
    item1.user = u1
    tagsForUser1.each {
        t = Tag.findByName(it)
        if(!t) {
            t = new Tag(name:it).save()
        }
        item1.addToTags(new Tagging(user:u1,tag:t,taggable:item1))
    }
    item1.save(flush:true)
    
    //ITEM2 **************************************************
    item2 = new Taggable(name:'item2')
    item2.user = u2
    tagsForUser2.each {
        t = Tag.findByName(it)
        if(!t) {
            t = new Tag(name:it).save()
        }
        item1.addToTags(new Tagging(user:u2,tag:t,taggable:item2))
    }
    item2.save(flush:true)
}

Initial URL

                                

Initial Description

                                

Initial Title
Tagging in Grails: many-to-many

Initial Tags
groovy

Initial Language
Groovy