Вопрос

In Grails, I have two domain classes having many to many relationship

class VisitingUser
{
  String name
  static hasMany = [visitedCountries:VisitedCountry]
  static belongsTo = VisitedCountry
}

class VisitedCountry
{
  String countryName
  static hasmany=[users:VisitingUser]
}

I want all those users who visited country "india" AND "usa" both.

Currently I am solving this problem by getting two list of visitingUsers, one for "india" and other for "usa" and then putting them in a Set.

I want a solution with using createCriteria or dynamic finder.

Это было полезно?

Решение

I don't think this is possible with a criteria query, and it's definitely not possible with a dynamic finder. Here's a solution with HQL though:

VisitingUser.executeQuery('''
select distinct u from VisitingUser u where
u in (
   select u from VisitingUser u join u.visitedCountries country where country.countryName = 'usa'
)
and u in (
   select u from VisitingUser u join u.visitedCountries country where country.countryName = 'india'
)
''')

Two unrelated things - VisitedCountries should be called VisitedCountry (although the set name visitedCountries makes sense because it will potentially have multiple elements), and the relationship should be many-to-many.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top