所以我在下面有这个查询,它可以工作,但是我想避免显式地编写HQL并使用Grails / GORM中可用的方法。我该如何实现?

我有一个包含许多RSVP(每个人1个)的 Activity 。该查询正在查找特定用户尚未针对哪些事件进行rsvp。它根据user_id左连接Rsvp表和事件表。我检查Rsvp是否为空。

def events = Event.executeQuery("""
        SELECT event
        FROM Event AS event
        LEFT JOIN event.rsvps AS rsvp
            WITH rsvp.user.id = ?
        WHERE event.active = 1
        AND event.startDate >= ?
        AND rsvp.id IS NULL
    """, [(long)1, new Date().clearTime()]);

谢谢

最佳答案

有一个近似值。我怀疑LEFT OUTER JOIN是否可以使用,但应该可以给您一个想法:

import static org.hibernate.sql.JoinType.*

def events = Event.withCriteria {
    createAlias('rsvps', 'r', LEFT_OUTER_JOIN)
    // I'm not sure about the following line. Aliases change things a bit
    // Besides, it conflicts with the isNull().
    eq('r.user.id', 1)
    eq('active', 1)
    ge('startDate', new Date().clearTime())
    isNull('r.id')
}

我的其中一篇文章可能对您有所帮助:http://emmanuelrosa.com/articles/gorm-for-sqladdicts-where-clause/

09-30 12:41
查看更多