急切加载“二级”关联对象时出现问题

Posted

技术标签:

【中文标题】急切加载“二级”关联对象时出现问题【英文标题】:Trouble on eager loading "second degree" associated objects 【发布时间】:2012-03-26 15:44:54 【问题描述】:

我正在运行 Ruby on Rails 3.1。我想通过应用一些条件来急切地加载“二级”关联对象,但我遇到了麻烦。

看来我已经通过使用解决了part of my issue:

article_categories =
  article
    .categories
    .includes(:comments => [:category_relationships])
    .where(:category_relationships => :user_id => @current_user.id)

其中涉及的类说明如下:

class Category < ActiveRecord::Base
  has_many :comment_relationships
  has_many :comments,
    :through => :comment_relationships

  ...
end

class Comment < ActiveRecord::Base
  has_many :category_relationships
  has_many :categories,
    :through => :category_relationships

  ...
end

上面的代码(好像做对了):

    通过关注has_many :through :category_relationships 关联(即通过关注.where(:category_relationships =&gt; :user_id =&gt; @current_user.id) 条件)加载所有categories; 渴望加载所有article.comments.where(:user_id =&gt; @current_user.id)

不过,我想多做一些:

    to order 通过category_relationships 中存在的:position 属性检索categories,以便生成的article_categories 按位置排序; 到急切加载还有category_relationship对象user_id == @current_user.id,因为上面的代码没有做到这一点。

如何利用即时加载来实现这一点?

【问题讨论】:

您在CategoryComment 之间使用两个不同的连接表有什么原因吗? 【参考方案1】:

解决办法:

    .order("category_relationships.position")

    想象急切加载是带有一些过滤的笛卡尔积,因此“where”正在过滤包含的最终结果(实际上是左连接)。但是可以使用带有子查询的where 来完成,该子查询首先会按用户过滤类别,然后可以删除您的位置。

【讨论】:

你能举个例子吗?

以上是关于急切加载“二级”关联对象时出现问题的主要内容,如果未能解决你的问题,请参考以下文章

使用 HQL 急切加载嵌套关联

“过滤”急切加载的数据时出现问题

如何急切加载具有条件和当前用户的关联表?

Hibernate:为啥 FetchType.LAZY 注释的集合属性急切地加载?

Sequelize 关联 hasOne,belongsTo

尝试复制 pyside 对象时出现问题