【问题标题】:Sequel join: ".id" is returning the id of the the other table续集连接:“.id”正在返回另一个表的 id
【发布时间】:2013-10-14 20:13:44
【问题描述】:

我有一个使用 Ramaze 和 Sequel 的 Ruby 应用程序。

我有 TagTagging 有这种关系的类:

class Tag < Sequel::Model
  one_to_many  :taggings, :class => 'Thoth::Tagging'

class Tagging < Sequel::Model(:taggings)
  many_to_one :tag, :class => 'Thoth::Tag'

我想返回一个标签列表,按受欢迎程度排序,标签最多的标签(过滤掉少于三个标签的标签)。我是这样做的:

tags = .left_outer_join(:taggings, :tag_id => :id).group(:tag_id).having("count(*) > 2").order("count(*) desc").all

这确实返回了似乎是标签对象的东西,但是当我在它们上调用 .id 时,我得到了指向标签的标签的 id,而不是标签本身。

仔细观察,结果与常规发现完全不同:

> tag_regular = Tag[2]
=> #<Thoth::Tag @values={:title=>nil, :position=>nil, :parent_id=>1, :name=>"academic", :id=>2}>

> tag_from_join = Tag.join(:taggings, :tag_id => :id).group(:tag_id).having("count(*) > 2").order("count(*) desc").all.select{|tag| tag.name == "academic"}.first
=> #<Thoth::Tag @values={:tag_id=>2, :post_id=>5, :title=>nil, :position=>nil, :parent_id=>1, :name=>"academic", :id=>1611, :created_at=>nil}>

在这两种情况下,我都会得到一个 Thoth::Tag,但值是完全不同的,这取决于我想的连接中的不同字段。

我真正需要做的就是获取一个按标签数量排序的常规标签对象列表,但是以一种有效的单查询方式。有没有更好的办法?

【问题讨论】:

    标签: ruby join sequel ramaze


    【解决方案1】:

    默认选择是*,因此您从tagstaggings 中选择列。如果您在两个表中都有 id 列,因为 Sequel 将记录作为由列名作为键的哈希返回,taggings 表中的列将覆盖 tags 表中具有相同名称的列。

    如果您只想要来自tags 的列,请将select_all(:tags) 添加到数据集。

    Sequel master 分支有一个table_select 插件,默认情况下会处理这种情况。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-08
      • 1970-01-01
      • 2014-07-29
      • 2022-01-07
      • 1970-01-01
      • 2011-05-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多