1

我是 Grails、Groovy 和 GSP 的新手。

我有一个域类“ProductCategory”。

class ProductCategory {

    static constraints = {
    }

    static mapping = {
        table 'product_category';
        version false;
        cache usage: 'read-only';
        columns {
            parent column: 'parentid';
            procedure column: 'procid';
        }

    }

    static hasMany = [children:ProductCategory];

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

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

每个类别都可以有一个父级。我正在使用现有的数据库,并且该表有一个“parentid”列来执行此操作。当类别没有父级(根级别)时,其 parentid 为 0。

我有一个 GSP 试图显示有关父母的数据(如果有)。

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

我的印象是这将测试存在。如果类别确实有父类别,它工作正常,但是一旦 parentid=0,它就会爆炸。

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

我试图检查 ==0,但它没有用,我认为是因为“父级”应该是一个对象。

那么我怎样才能让它假设 parentid=0 与 parent=null 或 NO parent 相同?

谢谢

4

3 回答 3

1

我想我可能已经找到了答案:

parent column: 'parentid', ignoreNotFound: true;

ignoreNotFound 不在文档中,但它似乎有效!

于 2010-01-27T03:29:29.520 回答
0

parentid不应该等于 0。应该是null

我在您的问题中不明白的是,您如何才能拥有 parentid == 0 ?

于 2010-01-27T01:11:10.967 回答
-1

您不需要手动处理 parentid。一旦您定义了这样的域类:

Class Foo {
    Bar bar
}

Gorm/Grails 会自动为你创建一个外键列。如果您定义属性可为空:

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

...您可以将其设置为 null 并测试是否为 null:

def f = new Foo(bar:null)
if (f.bar == null) { ... }
于 2010-01-27T12:37:15.680 回答