Question

I have two domain classes:

class A {
    int id
    static hasMany = [bs: B]
}

class B {
    int id
}

Can I use GORM to find all A instances that are related to a B instance with a given id?
I tried:

A.findAllByBs(B.get(bid))

But I get the following error:

Class: java.sql.SQLException
Message: No value specified for parameter 1
Was it helpful?

Solution

From the Gorm documentation

Querying Associations

Associations can be queried by having a node that matches the property name. For example say the Account class had many Transaction objects:

class Account {
   …
   static hasMany = [transactions: Transaction]
   …
}

We can query this association by using the property name transaction as a builder node:

def c = Account.createCriteria()
def now = new Date()
def results = c.list {
    transactions {
        between('date', now - 10, now)
    }
}

The above code will find all the Account instances that have performed transactions within the last 10 days. You can also nest such association queries within logical blocks:

def c = Account.createCriteria()
def now = new Date()
def results = c.list {
    or {
        between('created', now - 10, now)
        transactions {
            between('date', now - 10, now)
        }
    }
}

So this should work:

def c = A.createCriteria()
def results = c.list {
    bs {
        // Conditions...
    }
}

Hope it helps or give any hint of how to follow.

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