【问题标题】:Want to sort by association records count in Datamapper想要在 Datamapper 中按关联记录计数排序
【发布时间】:2010-12-02 16:33:04
【问题描述】:

假设我有以下 DataMapper 资源:

class Post
  include DataMapper::Resource 

  has n, :comments
  ...

end  

class Comment
  include DataMapper::Resource 

  belongs_to :post
  ...

end

要获得有序的帖子列表,我知道你可以这样做:

@posts = Posts.all(:order => :date.desc)

但是假设我想显示所有的帖子,按他们有多少 cmets 降序排列。我该怎么做?

【问题讨论】:

    标签: ruby sorting associations datamapper


    【解决方案1】:

    您也可以使用 sort_by,它调用单独的查询:

    @post = Post.all(:order => :date.desc).sort_by { |post| -post.comments.count }
    

    如果要更改顺序,可以去掉减号:

    @post = Post.all(:order => :date.desc).sort_by { |post| post.comments.count }
    

    这在语法上很好,但就像adamaig 指出的那样,它的性能可能比缓存数据库中的 cmets 数量更差,因为您要添加一个额外的 SQL 查询。

    【讨论】:

      【解决方案2】:

      出于性能原因执行此操作的一个好方法是缓存帖子的 comment_count 值,然后它会为您提供一个用于 :order 的属性,可能类似于 :order => :comment_count_cache.desc 。这很容易通过为 Comment 模型添加创建后挂钩来设置。

      【讨论】:

        【解决方案3】:

        我相信你要生成的SQL是:

        SELECT posts.*, COUNT(comments.id) AS comments_count FROM posts
        JOIN comments ON posts.id = comments.post_id
        GROUP BY posts.id ORDER BY comments_count DESC
        

        据我所知,这不是您可以使用 Query 类以编程方式执行的操作。只需为此放入 SQL。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-12-26
          • 1970-01-01
          • 2011-04-21
          • 1970-01-01
          • 1970-01-01
          • 2017-07-24
          • 1970-01-01
          相关资源
          最近更新 更多