mowwwalker
mowwwalker

Reputation: 17344

Grails GORM criteria on null association

I have a domain object with an associated domain object which I'd like to be able to search on as part of a query.

Using the Book model as an example, I'd have:

public class Book{
    Author author
    String title
}

public class Author{
    String name
}

.. and want to filter like:

def book = Book.withCriteria{
    or{
        ilike(title, "%" + params.filter + "%")
        author{
            ilike("name", "%" + params.filter + "%")
        }
    }
}

The problem I'm having is that if I include author in the query, then any "Books" with a null author will not be returned, even if the title matches.

Upvotes: 0

Views: 808

Answers (1)

Emmanuel Rosa
Emmanuel Rosa

Reputation: 9885

That's likely due to the implicit inner join being created between Book and Author. Try using a left outer join like this:

def book = Book.withCriteria{
    createAlias 'author', 'auth', org.hibernate.sql.JoinType.LEFT_OUTER_JOIN
    or{
        ilike(title, "%" + params.filter + "%")
        ilike("auth.name", "%" + params.filter + "%")
    }
}

Upvotes: 1

Related Questions