Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the ID of a one-to-many loaded object without another trip to the DB with GORM

I have to GORM domains, A & B, that relate to database tables. A has a one-to-many relationship with B. Because of this, the classes look similar to:

class A {
   B b
   Long id
}

class B {
   Long id
}

When I retrieve an instance of A the ID of the corresponding instance of B is retrieved from the database. However, when I attempt to access that ID via something like:

A a = A.get(11)
Long bid = a.b.id

the whole object is loaded from the database. In some cases I only want the ID of B (which has already been retrieved) and do not want to load the whole instance from the database. Is there a way to get the ID from B without going back and fetching the whole object.

NOTE: I know that it is doing an extra fetch on the line with a.b.id above because I can see the SQL being generated since I turned on the loggingSql option in my DataSource file.

like image 829
mfollett Avatar asked Aug 29 '11 16:08

mfollett


1 Answers

Instead of:

Long bid = a.b.id

use:

Long bid = a.bId

like image 54
Joshua Moore Avatar answered Oct 23 '22 18:10

Joshua Moore