鉴于:
create_table(:foos) do
primary_key(:id)
String(:name)
end
create_table(:bars) do
primary_key(:id)
String(:name)
end
create_table(:foos_bars) do
primary_key(:id)
foreign_key(:foo_id, :foos)
foreign_key(:bar_id, :bars)
String(:name)
end
class Foos < ROM::Relation[:sql]
dataset :foos
def with_bars(id)
prefix('foos').qualified.select(
:foos__id, :foos__name
).select_append(
:bars__id, :bars__name
).left_join(
:foos_bars, foos_bars__bars_id: :foos__id
).left_join(
:bars, bars__id: :foos_bars__bars_id
).where(foos__id: id)
end
end
class FoosModel
include Virtus.model
attribute :id
attribute :name
attribute :bars
end
class BarsModel
include Virtus.model
attribute :id
attribute :name
attribute :foos
end
我在 ROM 文档中显示(但未在其中解释)的关键字上尝试了许多随机变体,但无济于事。这是将文档的字面解释为 Foos 的映射器,它不起作用:
class FoosMapper < ROM::Mapper
relation :foos
register_as :foos
model Foo
prefix('foos')
attribute :id
attribute :name
group :bars do
model Bar
attribute :id, from: :bar
attribute :name, from: :bar
end
end
如何编写一个映射器(或修改关系以与映射器一起工作)以获得具有 bar 属性的 foo 的简单结果,该属性具有由 foos_bars 表链接的所有条?