9

我对 grails 标准构建器有疑问,我想对与父表示例一对多关系的表上的列进行投影:

Car.createCriteria() { 
   projections { 
     property('name') 
     property('wheels.name')// ???? 
   }

   join 'wheels' 
   //or wheels {} ???
}

或类似的东西存在?我认为这是别名的基本问题

4

2 回答 2

22

我假设以下域类:

class Car {
  String name
  static  hasMany = [wheels : Wheel]
}

class Wheel {
  String name
  static belongsTo = [car : Car]
}

我还假设这是所需的输出:

CarName WheelName
Car1    Wheel1
Car1    Wheel2
Car2    Wheel3

在这种情况下,您可以这样做:

void testCarProjectionItg() {
  def car1 = new Car(name: 'Car1').save()
  def car2 = new Car(name: 'Car2').save()

  def wheel1 = new Wheel(name: 'Wheel1')
  def wheel2 = new Wheel(name: 'Wheel2')
  def wheel3 = new Wheel(name: 'Wheel3')

  car1.addToWheels wheel1
  car1.addToWheels wheel2     
  car2.addToWheels wheel3
  wheel1.save()
  wheel2.save()
  wheel3.save()
  car1.save()
  car2.save()

  println Wheel.withCriteria {
    projections {
      property('name')
        car {
          property('name')
        }
    }       
  }
}

--Output from testCarProjectionItg--
[[Wheel1, Car1], [Wheel2, Car1], [Wheel3, Car2]]

在这种情况下,我更喜欢 HQL 查询:

println Wheel.executeQuery("select car.name, wheel.name from Car car inner join car.wheels wheel")
--Output from testCarProjectionItg--
[[Car1, Wheel1], [Car1, Wheel2], [Car2, Wheel3]]
于 2011-05-05T18:28:18.537 回答
10

只做:

Car.createCriteria().list() { 
    createAlias("wheels","wheelsAlias")
    projections { 
        property('name') 
        property('wheelsAlias.name')
    }
}

还是我错过了什么?

于 2012-06-12T23:43:34.573 回答