开发者

Grails: parent id null when objects listed by it

First time here, and new to Grails, I have a weird issue with a one-to-many relationship.

I'm creating a Grails application to provide services to a website and smartphone applications.

I tried my best to make a parent service which 开发者_StackOverflowcan handle generic actions (create, get, modify, list, delete...) from which I can inherit more specific services.

The issue I'm facing comes from the list action. I construct a withCriteria request from the parameters the callers send me.

I have two domains :

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

class B {
  static belongsTo = [a:A]
}

What I need is to list class B objects belonging to an A object, my generic list action generates this :

List objects = B.withCriteria() {
  createAlias("A","A")
  eq("A.id", myId)
}

Everything works fine, but thing is, I made a generic toJSON() method which creates a JSON response from a domain instance. In order to do so, I iterate through a String list which contains the name of the domain properties I want to add in my JSON response. Then I access them like this :

objects[0]."$propertyName"

If my object contains references to other objects, I want to add the id of those in the JSON response.

Those ids can be accessed using this syntax :

objects[0].aId

But the damn thing is null ! If I access it doing :

objects[0].a.id

I have the right parent id !

I made some tests and if I don't filter B objects by an A object, then I can access the parent id the way I want to do it, ie :

List objects = B.withCriteria() {}
objects[0].aId

Any idea of what's going on here ?

Thank you.


removed some stuff because of your edits. I'm not sure why you need to use criteria for this kind of query.

def car = new Car()
car.addToWheels(new Wheel())
car.save(flush:true)

def theCar = Car.get(1)
def wheels = car.wheels

OR:

def wheels = Wheel.findAllByCar(carInstance).

OR: (and I don't know why you would want to)

def carInstance = Car.get(carId)
List wheels = Wheel.withCriteria {
   eq("car", carInstance)
}
assertTrue(wheels[0].car.id == carId)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜