我希望在this Django example和Postgres中以多对多关系存储额外数据,类似于Sequel。
在我的例子中,每个人都有自己工作的地方,以及他们在那里工作的时间。每个人可以在同一个地方工作不同的时间。例如......
Joe works at The Bar Mon, Wed & Fri 9-5pm.
Joe also works at The Bar Saturday noon-midnight.
Joe works at Some Pub Sunday 12-5.
Joe started working at The Bar 2013-12-07
Joe started working at Some Pub 2014-12-23
我想知道如何设置表格和模型以使其尽可能不尴尬。目前我有这样的架构。
create_table(:people) do
primary_key :id
String :name
end
create_table(:works) do
primary_key :id
String :name
end
create_table(:employments) do
primary_key :id
foreign_key :work_id, :work, null: false,
foreign_key :person_id, :people, null: false,
Date :started
end
create_table(:hours) do
primary_key :id
foreign_key :employment_id, :employments, null: false
String :dow, null: false,
Time :start, null: false, only_time: true
Time :end, null: false, only_time: true
end
我应该如何创建模型关联以将它们连接在一起?理想情况下,我希望能够说出像......
joes_hours_at_some_pub = joe.employment("Some Pub").hours
...无需通过中间联接表。
答案 0 :(得分:0)
Sequel's advanced association doc就是一个例子。定义就业模型并使用:join_table通过它创建关系。
class Person < Sequel::Model
one_to_many :employments,
many_to_many :works, join_table: :employments
# This allows joe.employment(work).hours
def employment(work)
employments_dataset.where(work_id: work.id)
end
end
class Work < Sequel::Model
one_to_many :employments,
many_to_many :people, join_table: :employments
end
class Employment < Sequel::Model
many_to_one :person
many_to_one :work
one_to_many :hours
end
class Hours < Sequel::Model
many_to_one :practice
end