【问题标题】:Rails SQL Join two tables, One table has two columns with ids of other table, I need to get names of these idsRails SQL加入两张表,一张表有两列,另一张表的ID,我需要得到这些ID的名字
【发布时间】:2015-04-28 19:12:24
【问题描述】:

这是我的关联模型:

class ProjectLineThreshold < ActiveRecord::Base
  belongs_to :project_line
  belongs_to :source, class_name: 'Language'
  belongs_to :target, class_name: 'Language'
end

ProjectLineThreshold 表有这些列(:id, :source_id, :target_id, :score)。我需要通过语言表中的 source_id 和 target_id 添加语言名称。

我想出了这个说法:

thresholds = self.project_line_thresholds.joins(:source, :target)
    .select('project_line_thresholds.id, project_line_thresholds.source_id, project_line_thresholds.target_id,
      project_line_thresholds.score, languages.name as source_name, languages.name as target_name')

但我的目标和源名称相同。什么是正确的连接语句,或者我做错了?

【问题讨论】:

    标签: sql ruby-on-rails postgresql join


    【解决方案1】:

    不需要select语句,通过关联获取名字即可:

    ProjectLineThreshold.includes(:source, :target).each do |plt|
      puts "Source name: #{plt.source.name}"
      puts "Target name: #{plt.target.name}"
    end
    

    请注意,includes 只是确保预加载关联的记录,否则它将在每次循环迭代期间运行单独的查询来检索源和目标。

    【讨论】:

      【解决方案2】:

      以下查询只会命中数据库一次:

      self.project_line_thresholds
        .joins(:source, :target)
        .includes(:source, :target)
        .map {|plt| [plt.id, plt.source_id, plt.target_id, plt.score, source.name, target.name]}
      

      【讨论】:

        【解决方案3】:

        只有当您想要预先加载数据时才需要一个语句,即对所有内容运行一个 sql 查询。已经提供了这方面的答案。

        否则,你可以使用active record提供的关联方法,例如:

        @project_line_threshold.source.name
        @project_line_threshold.target.name
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-05-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多