【问题标题】:How to remove a item from a def list in grails如何从grails中的def列表中删除项目
【发布时间】:2015-12-10 12:52:41
【问题描述】:

我正在尝试从列表中删除一个项目。我有一个名为 InvItem 的表和另一个名为 InvItemLoc 的表。当我添加一个项目时,InvItem 表的 id 用作 InvItemLoc 表中的外键。但是当我删除一个项目时,子表行不会被删除。现在我需要通过当前位于 InvItem 表中并具有特定组织的 InvItem id 生成 InvItemLoc 表的列表。但是,当我要检查它是否将 InvItemLoc 与 InvItem 表匹配时,它会给出此错误 -> No row with the given identifier exists: [inv.InvItem#9666] 。现在有人可以帮我解决这个问题吗?!!!这是我在下面的尝试::

def items = InvItemLoc.findAllByAaOrgId(aaOrg)
                List<InvItemLoc> found = new ArrayList<InvItemLoc>();
                for(InvItemLoc item : items){
                    def invItem = InvItem.findById(item.invItemId.id)
                    if(!invItem){
                        found.add(item);
                    }
                }
                items.removeAll(found);

这行报错>> def invItem = InvItem.findById(item.invItemId.id)

编辑 :: 域

我的 InvItemLoc 域如下所示 >>>

class InvItemLoc {
    static mapping = {
        ...
    }

    Long id
    InvItem invItemId
    ...

    static constraints = {
        ...

    }
}

InvItem 域如下所示 >>>

    class InvItem  {
    static mapping = {
        ...
    }

    Long id
    ...

    static constraints = {
        ...
    }

        String toString() {
        ...
    }
}

【问题讨论】:

  • 听起来您可能会受益于InvItemInvItemLoc 之间的双向关联。您的域类是什么样的?
  • @EmmanuelRosa 感谢您的回复。我已经用域类更新了我的帖子。你现在能帮忙吗?!!

标签: hibernate grails grails-orm grails-2.0


【解决方案1】:

您可以在域类之间创建one-to-many 关联。然后,当您删除父级时,Grails 可以为您删除子级。 InvItemLoc 需要添加 belongsTo 静态属性并删除 invItemId 属性。 InvItem 需要添加 hasMany 静态属性。

class InvItemLoc {
   ...
   static belongsTo = [item: InvItem]
}

class InvItem  {
    static hasMany = [locations: InvItemLoc]
    ...

}

创作

这改变了域类的创建和保存方式。

def loc = new InvItemLoc()
// set loc properties.

def item = new InvItem()
item.addToLocations(loc)
// Set other item properties.

item.save()

简而言之,您将位置添加到项目,然后保存项目,然后保存位置。

删除

然后,您可以像这样简单地删除:item.delete()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-19
    • 2016-03-12
    • 1970-01-01
    • 2022-12-20
    • 2017-08-31
    • 2020-02-16
    相关资源
    最近更新 更多