开发者

Grails - check if item has parent

开发者 https://www.devze.com 2022-12-18 17:16 出处:网络
I\'m new to Grails, Groovy and GSP. I have a domain class \"ProductCategory\". class ProductCategory { static constraints = {

I'm new to Grails, Groovy and GSP.

I have a domain class "ProductCategory".

class ProductCategory {

    static constraints = {
    }

    static mapping = {
        table 'product_category';
        version false;
        cache usage: 'read-only';
        columns {
            parent column: 'parentid';
            procedure colu开发者_如何学Pythonmn: 'procid';
        }

    }

    static hasMany = [children:ProductCategory];

    ProductProcedure procedure;
    Integer lineorder;
    String name;
    ProductCategory parent;
    String templatelink;
    char offline;

    String toString() {
        return id + " (" + name + ")";
    }
}

Each category CAN have a parent. I am using an existing database, and the table has a column 'parentid' to do that. When a category has no parent (root level), its parentid is 0.

I have a GSP trying to show data about the parent if any.

<g:if test="${category.parent}">
hello
</g:if>

I was under the impression that this would test for existence. It works fine if the category DOES have a parent, but as soon as parentid=0, it blows up.

No row with the given identifier exists: [ProductCategory#0]

I tried to check for ==0, but it didn't work, I assume because 'parent' is supposed to be an object.

So how can I make it so that it assumes that parentid=0 is the same as parent=null, or NO parent?

Thanks


I think I may have found the answer:

parent column: 'parentid', ignoreNotFound: true;

ignoreNotFound is nowhere on the documentation, but it seems to work!


parentid should not be equal to 0. It should be null.

What I don't understand in your question, is how can you have parentid == 0 ?


You don't need to handle the parentid manually. As soon as you define a domain class like this:

Class Foo {
    Bar bar
}

Gorm/Grails will automatically create a foreign key column for you. And if you define the property nullable:

Class Foo {
     Bar bar
     static constraints = {
         bar(nullable:true)
     }
}

...you can just set it to null and test for null:

def f = new Foo(bar:null)
if (f.bar == null) { ... }
0

精彩评论

暂无评论...
验证码 换一张
取 消