如何避免多态关联 [英] how to avoid polymorphic associations

查看:99
本文介绍了如何避免多态关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于您必须实现一个新闻提要,就像在社交网络中看到的一样,例如facebook. 当前,我正在使用具有多态关联的News类,该关联可以是任何类型,例如图像,注释,友谊,GroupMembership等.无论何时创建对象,也创建新闻.它在AR(ActiveRecords)上可以正常工作,但是当我切换到DM(DataMapper)或Sequel时遇到麻烦,因为它们都不自然地支持多态关联并且不鼓励使用它.

Given you have to implement a news feed like the one seen in social networks, ex facebook. Currently I'm using a News class which has a polymorphic assocation which can be of any kind like Image, Comment, Friendship, GroupMembership, etc. Whenever an Object is created, as News is created too. It's working fine with AR(ActiveRecords) but I get into trouble when I'd switch to DM(DataMapper) or Sequel as both don't natevily support polymorphic associations and discourage it's usage.

一种解决方法是使用带有大量UNION的大型SQL子句来合并所有应视为新闻的不同表.但这有一些缺点,特别是性能会很糟糕.

One workaround would be to use a big SQL clause with lot's of UNIONs to merge all the different tables which should be considered as news. But this has some drawbacks, escpecially performance would be terrible.

所以我想知道如何在没有多态关联的情况下解决问题,同时又能获得良好的性能,而又没有其他缺点,例如可以将元数据添加到新闻中?

So I wonder how to solve without polymorphic associations while still getting good performance and no other drawbacks, like having the possibility of adding meta data to a news?

推荐答案

免责声明:我是Sequel的首席开发人员.

Disclaimer: I'm the lead developer of Sequel.

最好的解决方法通常取决于您要对数据进行哪种类型的处理.一种解决方法是为所有可能的关系提供外键列:

The best way to go about it usually depends on what types of things you want to do with the data. One way to go about it is to have foreign key columns for all possible relationships:

news:
  id
  ... (Other columns)
  image_id
  comment_id
  friendship_id
  group_membership_id

与具有通用外键和存储类名称相比,以这种方式执行操作确实没有性能差异.对于延迟加载,您只需选择一个非nil/NULL的外键字段,然后选择适当的关联即可加载.对于按表查询急切加载,您只需一次加载所有关联.这也更加灵活,因为您可以急切地使用JOIN进行加载,而这是多态方法无法实现的.此外,您还可以获得真正的参照完整性的好处.

There is really no performance difference in doing things this way versus having a generic foreign key and storing a class name. For lazy loading, you just pick the one foreign key field that's not nil/NULL, and choose the appropriate association to load. For query-per-table eager loading, you just load all associations at once. This also is more flexible in that you can eagerly load using JOINs, which isn't possible with the polymorphic approach. Plus, you get the benefit of real referential integrity.

一个缺点是,如果您以后想添加更多的关联类型,则需要向表中添加外键.

The one downside is that if you want to add more association types in the future, you need to add foreign keys to the table.

这篇关于如何避免多态关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆