如何使用 Sequel 从其他表中获取数据

How to get data from other tables using Sequel

我使用 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 table 中有一个 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 table 中至少获得 foo_name,基于foo_id 那是在酒吧 table?

甚至更多,如果有更长的关联怎么办,假设有另一个外键,例如 baz_id,在链接到 Baz table 的 Foo table 中,并且在同一个 API 中,我还想根据各自 table 中的外键关联从 Foo 和 Baz table 中获取所有信息。

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

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

因此,在 Bar 的单个实例上,您可以执行以下操作:

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

如果你想为完整列表做这件事,就像你的例子一样,你会想在 class 上调用它。请注意,如果您在数组上调用它,这将不起作用,因此您必须在将其转换为数组之前在数据集上调用它。

# 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}})