我正在尝试从列表中删除项目。我有一个名为 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() {
...
}
}
您可以在域类之间创建一对多关联。当您删除父级时,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()