【问题标题】:Grails - check if item has parentGrails - 检查项目是否有父项
【发布时间】:2011-01-09 18:12:38
【问题描述】:

我是 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,但没有成功,我认为是因为 'parent' 应该是一个对象。

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

谢谢

【问题讨论】:

  • 你在哪里设置 parentid=0 ?
  • 我没有设置。这是一个只读应用程序,当类别没有父级时,我现有的数据的 parentid=0。

标签: grails groovy gsp


【解决方案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) { ... }

【讨论】:

  • 再一次,这个应用程序是建立在现有数据库之上的,具有现有数据。我不能让 Grails 为我创建/修改任何数据库模式。
【解决方案2】:

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

parent column: 'parentid', ignoreNotFound: true;

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

【讨论】:

    【解决方案3】:

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

    你的问题我不明白,你怎么能有 parentid == 0 ?

    【讨论】:

    • 因为这是建立在现有的应用程序和数据库架构之上的。就像我说的那样,在现有架构中,parentid=0 表示没有父级。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多