5

我正在尝试从以下两个表(在 SQLite 中)中以嵌套形式检索数据

DB = Sequel.sqlite('database.sqlite')

DB.create_table? :artists do
    primary_key     :id
    String          :name
end

DB.create_table? :albums do
    primary_key     :id
    String          :title
    foreign_key     :artist_id,
                    :artists,
                    :key => :id
end

artists = DB[:artists]
albums = DB[:albums]

id1 = artists.insert(:name => 'Mike')
id2 = artists.insert(:name => 'John')

albums.insert(:title => 'Only You', :artist_id => id1 )
albums.insert(:title => 'Only Us', :artist_id => id1 )
albums.insert(:title => 'Only Me', :artist_id => id2 )

我试图得到的输出 -

[
  {
    :id => 1,
    :name => 'Mike'
    :albums => [
      {
        :id => 1,
        :title => 'Only You'
      },
      {
        :id => 2,
        :title => 'Only Us'
      }
    ]
  },
  {
    :id => 2,
    :name => 'John'
    :albums => [
      {
        :id => 3,
        :title => 'Only Me'
      }
    ]
  }
]

我已经尝试过“渴望”加载-

class Artist < Sequel::Model(:artists)
  one_to_many  :db[:albums], :key => :artist_id
end

class Album < Sequel::Model(:albums)
  many_to_one  :artist, :key => :artist_id
end


Artist.eager(:albums).all{ |a| p a }

但这没有用。

谁能指出我正确的方向?

4

2 回答 2

4

Artist.eager(:albums).all确实急切地加载专辑,但{|a| p a}不会显示专辑(因为Sequel::Model#inspect只显示当前模型的值,而不是任何关联的对象)。用于{|a| p [a, a.albums]}查看相册是否已加载。

如果你想产生你描述的哈希:

Artist.eager(:albums).all.map do |a|
  a.values.merge(:albums=>a.albums.map{|al| al.values})
end
于 2012-11-20T16:58:25.720 回答
2

您可以向 Artist 添加一个方法以按照您想要的方式输出它

class Artist < Sequel::Model(:artists)
  one_to_many  :albums, :key => :artist_id

  def my_hash
    to_hash.merge!(
        {
            :albums => albums.map{|a| 
                a.to_hash.reject!{ |k,v| 
                    k==:artist_id
                }
            }
        }
    )
  end
end

class Album < Sequel::Model(:albums)
  many_to_one  :artist, :key => :artist_id
end

records = Artist.all.map{ |a| a.my_hash }
p records

而不是使用reject!它会更干净,而是添加一个my_hashAlbum 的方法来返回一个没有 的哈希:artist_id,但你明白了。这输出:

[
  {
    :albums=>[
      {
        :title=>"Only You", 
        :id=>1
      }, 
      {
        :title=>"Only Us", 
        :id=>2
      }
    ],
    :name=>"Mike",
    :id=>1
  },
  {
    :albums=>[
      {
        :title=>"Only Me", 
        :id=>3
      }
    ], 
    :name=>"John", 
    :id=>2
  }
]
于 2012-11-20T15:19:51.570 回答