Grayls count children from one to many in a domain class

I have a one-to-many relationship:

class Author {
    String name
    static hasMany = [books:Book]
    static constraints = {
    }
}

class Book {
    String name
    static belongsTo = [author:Author]
    static constraints = {
    }
}

I want to be able to count the number of books belonging to the author in the author’s class, so the resulting generated MySQL table will look like this:

id | version | name | bookcount
-- | ------- | ---- | ---------
 1 |       0 | foo  |        15
 2 |       0 | bar  |         3
 3 |       0 | baz  |         7

... where bookcount is a specific field in the author's class:

class Author {
    String name
    int bookcount = ??
    static constraints = {
    }
}

EDIT 1: The account must be stored in the database.

+4
source share
2 answers

You can do the following using gorm events :

class Author {
    String name

    Integer bookCount = 0
    static hasMany = [books:Book]

    Integer getBookCount () {
        books?.size () ?: 0
    }

    void beforeUpdate () {
        bookCount = getBookCount ()
    }

    static constraints = {
    }
}

The method beforeUpdatewill be called before the object is updated in the database.

getBookCount() , . Book s, bookCount , save() d.

bookCount , .

def "explicitly persist book count" () {
    given:
    Author author = new Author(name:'author')
    author.save (failOnError: true)

    when:
    author.addToBooks (new Book(name:'book'))
    author.save (failOnError: true, flush: true)

    then:
    author.bookCount == 1
    author.@bookCount == 1
}
+1

, , , - , .

    def numberOfChildren()
{
    def result = Child.executeQuery("select count(*) from Child where parent = :parent", ["parent":this])
    def resultCount = result[0]
    return resultCount
}
+1

Source: https://habr.com/ru/post/1547461/


All Articles