【问题标题】:How to get data from other tables using Sequel如何使用 Sequel 从其他表中获取数据
【发布时间】:2015-09-05 15:50:00
【问题描述】:

我使用Sequel,我的 Sinatra 应用中有以下 2 个模型

# foo.rb
require 'sequel'

module Notes
  module Models
    class Foo < Sequel::Model
      plugin :json_serializer, naked: true
      plugin :validation_helpers

      one_to_many :bars

      def validate
        super

        validates_presence [:foo_name], message: "can't be empty"
      end
    end
  end
end


# bar.rb
require 'sequel'

module Notes
  module Models
    class Bar < Sequel::Model
      plugin :json_serializer, naked: true
      plugin :validation_helpers

      many_to_one :foo

      def validate
        super

        validates_presence [:bar_name], message: "can't be empty"
      end
    end
  end
end

Bar 表中有一个foo_id 外键。

我有一个 API 路由,您可以在其中获取所有条形图,或者如果传入参数,则仅获取特定条形图,如下所示:

app.get '/api/bars' do
  require_session
  bar_name = params[:bar_name]
  bar_model = Models::Bar

  if bar_name.nil?
    bar_model.all.to_json
  else
    bar_model.where(Sequel.ilike(:bar_name, '%' + bar_name + '%'))
      .all
      .to_json
  end
end

我想做但还没有弄清楚的是,我怎样才能从结果中的 Foo 表中也至少获得 foo_name,根据 Bar 表中的 foo_id 检索?

更重要的是,如果有更长的关联,比如说有另一个外键,例如 baz_id,在链接到 Baz 表的 Foo 表中,并且在同一个 API 中,我还想获取所有Foo 和 Baz 表中的信息基于这些表中的外键关联。

希望这是有道理的,非常感谢任何帮助。

【问题讨论】:

    标签: ruby sinatra sequel


    【解决方案1】:

    您可以使用 Sequel 的 to_json 方法的 :include 选项来执行此操作。您可以在设置 json_serializer 选项时在模型中指定此项,但也可以在实例上调用 to_json 时覆盖这些默认值。

    因此,在 Bar 的单个实例上,您可以这样做:

    Bar.first.to_json(include: {foo: {only: :foo_name}})
    

    如果您想为完整列表执行此操作,如您的示例中所示,您可能希望在课堂上调用它。请注意,如果您在数组上调用它,这将不起作用,因此您必须在将其转换为数组之前在数据集上调用它。

    # all models 
    Bar.to_json(include: {foo: {only: :foo_name}})
    
    # a subset of models
    Bar.where(Sequel.ilike(:bar_name, '%' + bar_name + '%'))
      .to_json(include: {foo: {only: :foo_name}})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-07
      • 2019-02-02
      • 1970-01-01
      • 2019-09-18
      相关资源
      最近更新 更多