简体   繁体   English

单向一对多

[英]grails unidirectional one-to-many

this has been bugging me, 这一直困扰着我,

lets say i have two model, category and product 可以说我有两个型号,类别和产品

class Category {
  static hasMany = [products : Product]
  String name
}
..
class Product {
  String name
}

now, i want to delete product, which happens to exist in many category. 现在,我想删除恰好存在于许多类别中的产品。 i came up with these lines in my product beforeDelete methods 在删除方法之前,我在产品中想到了这些行

def beforeDelete = {
  Category.list()?.each{
       it.removeFromProducts(this)
    }
}

now this may works, but the way i see it, thats a lots of query for one simple task. 现在这可能有效,但是按照我的看法,多数民众赞成在一个简单任务上进行大量查询。 i know i can get the same result just with a single line of sql string ("delete from category_product where product_id = ?"). 我知道我只需一行sql字符串就可以得到相同的结果(“从category_product中删除,其中product_id =吗?”)。 but im just curious, is there more sophisticated way to achieve this in grails? 但是我只是好奇,是否有更复杂的方法可以实现这一目标? (besides executing the sql string) (除了执行sql字符串)

You could add the following lines to the Category class 您可以将以下行添加到Category类

static mapping = {
    products cascade: "all-delete-orphan"
}

and call delete on Category instead. 然后在类别上调用删除。 Why are you using a unidirectional relation in this case? 在这种情况下,为什么要使用单向关系? Wouldn't it be better with a bi-directional one? 双向使用会更好吗? In the case above you iterate over all Categories each time you delete a Product which is a resource heavy operation (depending on you many categories you have of course), the better solution would be to find the Category via a bi-directional relation like this: 在上面的例子中,每次删除一个耗费资源的产品(当然取决于您拥有的许多类别)时,您都会遍历所有类别,更好的解决方案是通过这样的双向关系来找到类别:

class Product {
    String name
    static belongsTo = [category: Category]
}

That was you can easily get to Category from Product and delete it. 那就是您可以轻松地从Product转到Category并将其删除。

See this blog post on more hints and tips. 有关更多提示和技巧,请参见此博客文章

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM