怎么说?我不明白续集文档试图告诉我的是,如果两个模型连接在一个外键上,在一个模型A中是may_to_one情况下另一个模型的主键的情况下的关联。我一直在想:如果是many_to,_one,在一个方向,它必须是one_to_many在另一个方向.但续集提供了一个令人困惑的章节,目的是澄清这个主题,此外,还有一个我无法效仿的例子。
上面写着在一“里
如果要在两个模型之间建立1-1关系,其中一个表中的外键直接引用关联表,则必须在一个模型中使用many_to_one,在另一个模型中使用one_to_one。你怎么知道在哪种型号中使用哪一种?记住的最简单的方法是,表中有外键的模型使用many_to_one,而另一个模型使用one_to_one“
并继续提供这个奇怪的例子:
# Database schema:
# artists albums
# :id <----\ :id
# :name \----- :artist_id
# :name
class Artist
one_to_one :album
end
class Album
many_to_one :artist
end
在相册里我可能会发现几行指向同一个艺术家..。为什么艺术家不应该回顾他/她的所有专辑?续集“多古”在很多情况下都很难读懂,但这一章读起来很简单,但对我来说却毫无意义。
发布于 2018-03-19 16:31:17
对我来说同样的问题。
require "logger"
require "sequel"
db = Sequel.connect "postgres://localhost/postgres", :logger => Logger.new(STDOUT)
db.drop_table :artists, :cascade => true if db.table_exists?(:artists)
db.create_table :artists do
primary_key :id
foreign_key :album_id, :albums
end
db.drop_table :albums, :cascade => true if db.table_exists?(:albums)
db.create_table :albums do
primary_key :id
foreign_key :artist_id, :artists
end
class Artist < Sequel::Model(db[:artists])
one_to_one :album
end
class Album < Sequel::Model(db[:albums])
one_to_one :artist
end
artist_1 = Artist.create
album_1 = Album.create
artist_1.update :album => album_1
album_1.reload
puts album_1.artist.nil?
artist_2 = Artist.create
album_2 = Album.create
album_2.update :artist => artist_2
artist_2.reload
puts artist_2.album.nil?
我们可以通过将任何one_to_one
替换为many_to_one
来修复此示例。
class Album
many_to_one :artist
end
在这种情况下,不会使用artist.album_id
。
class Artist
many_to_one :albums
end
在这种情况下,不会使用album.artist_id
。
问题是,方法名称one_to_one
和many_to_one
是由底层的sequel
逻辑选择的,它们对用户不友好。
您可以为这些方法创建用户友好别名。我更喜欢在评论中使用它。例如:
db.create_table :artists do
primary_key :id
foreign_key :album_id, :albums
end
db.create_table :albums do
primary_key :id
end
class Artist < Sequel::Model(db[:artists])
many_to_one :album # I have album_id foreign key
end
class Album < Sequel::Model(db[:albums])
one_to_one :artist # I don't have artist_id foreign key
end
https://stackoverflow.com/questions/48047119
复制相似问题