【问题标题】:Sequel: exclude records that do not have associationsSequel:排除没有关联的记录
【发布时间】:2015-04-27 21:37:55
【问题描述】:

我有一个使用 Sequel ORM 的 Sinatra 应用程序,我试图在其中仅列出包含一个或多个帖子的类别。

所以,如果我在数据库中有两个类别; “Apples”和“Oranges”,以及一个分配给“Apples”的帖子,那么当我列出当前类别时,我只想提供“Apples”类别。

在费了很多力气之后,我终于设法让它与以下内容一起工作;

class Post < Sequel::Model
  many_to_one :category
end

class Category < Sequel::Model
  one_to_many :posts

   dataset_module do 
     def with_posts
       where(id: Post.select(:category_id))
     end
   end
end

@categories = Category.with_posts

如果在 Sequel 中有更好的方法,请告诉我。

【问题讨论】:

  • 你所拥有的可能是最好的方法。
  • 太好了,谢谢杰里米。

标签: ruby sinatra sequel


【解决方案1】:

试试 Jeremy 的计数器缓存https://github.com/jeremyevans/sequel_postgresql_triggers

# In your migration:
pgt_counter_cache :categories, :id, :posts_count, :posts, :category_id

# And in your code:
categories = Category.exclude(posts_count: 0).all

文档不是很好,所以这里是参数:https://github.com/jeremyevans/sequel_postgresql_triggers/blob/master/lib/sequel_postgresql_triggers.rb#L27

【讨论】:

  • 我在 Rails 中经常使用计数器缓存,所以我喜欢这个,而且我现在只使用 postgres,我不介意这种依赖。一定会看看这个。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-12
  • 1970-01-01
相关资源
最近更新 更多