0

I have a simple one-to-many association:

class Foo {
    int id
    Date someDate

    static hasMany = [
        bars: Bar
    ]
}

class Bar {
    Foo foo
    Date someDate

    static mapping = {
        .....
        columns {
            foo([:]) {
                column name: "id"
            }
        }
    }
}

Under normal circumstances, calling foo.bars will return all Bars, which is fine. But in this case I need to query using the someDate argument. I need to eagerly fetch the collection, but I'm not sure how to do this. I'd like to do something like this:

Foo.withCriteria {
    eq("id", someId)
    bars {
        eq("someDate", ?????)
    }
}

I'm not sure what to put in for the value though, since it's not known ahead of time, or if there's a better way to do it?

Alex Beardsley
  • 20,988
  • 15
  • 52
  • 67
  • You would put the variable there??? – James Kleeh Mar 20 '13 at 01:33
  • @JamesKleeh I think you missed the question. I wanted to join Bars and Foo by not only the PK but also on another Date field. So where the "?????" is, I didn't know what to put there in order to do that. – Alex Beardsley May 20 '13 at 17:40

1 Answers1

1

Filtering the list inside the parent class would be very confusing. If you managed to make an instance foo where foo.bars only had a subset of the list of Bars, things like foo.addToBars would have strange behavior, among other problems.

If you merely need to find the set of Bars that belong to a given Foo, filtered by their someDate property, you should be querying against the Bar class to begin with:

Bar.findAllByFooAndSomeDate(foo, dateVal)
Bar.findAllByFooAndSomeDateBetween(foo, startDate, endDate)

or:

Bar.findAll() {
    (foo.id == someId) && (someDate == dateVal)
}

etc.

codelark
  • 12,254
  • 1
  • 45
  • 49
  • There is a lot more to the query, I just reduced it for simplicity. I'm just trying to populate the object graph in a single query (if possible?) instead of doing multiple queries for each set I need filtered. What I just want to do is to fetch that collection based on the parent object's someDate property. But, your comment makes sense, where doing things with the list would be weird. – Alex Beardsley Mar 28 '13 at 15:20
  • If you're populating a complex graph, you're probably better off with HQL and projections. – codelark Mar 28 '13 at 15:23