如果我有两个表与many_to_many关系:
DB.create_table? :students do
primary_key :id
String :name
end
DB.create_table? :books do
primary_key :id
String :title
end
DB.create_table? :students_books do
Integer :num_days_borrowed
foreign_key :student_id,
:students,
:key => :id,
:allow_null => false
foreign_key :book_id,
:books,
:key => :id,
:allow_null => false
end
我有以下续集课程:
class Student < Sequel::Model(:students)
many_to_many :books,
:left_key => :student_id,
:right_key => :book_id,
:join_table => :students_books
def borrowed(bk)
add_book(bk)
end
end
class Book < Sequel::Model(:books)
many_to_many :books,
:left_key => :book_id,
:right_key => :student_id,
:join_table => :students_books
end
所以,现在我可以给这样的学生添加书籍了:
s1 = Student.create(:name => 'Hari')
b1 = Book.create(:title => 'Foundation')
s1.borrowed(b1)
我的问题是如何使用续集模型分配值并检索num_days_borrowed
属性?
答案 0 :(得分:1)
您需要向Sequel提供有关模型的更多信息。
在Student
和Book
模型中,在这些模型和联结表之间添加one_to_many
关系(引用联结表中的外键)。
然后创建一个StudentsBook
模型,您将在其中设置联结表与其他表之间的many_to_one
关系。
但首先,在联结表中设置主键:
DB.create_table :students_books do
# add columns, etc
primary_key [:student_id, :book_id]
end
然后将模型设置为如下所示:
class Student < Sequel::Model(:students)
many_to_many :books,
:left_key => :student_id,
:right_key => :book_id,
:join_table => :students_books
one_to_many :students_books, :key=>:student_id
def borrowed(bk)
add_book(bk)
end
end
class Book < Sequel::Model(:books)
many_to_many :books,
:left_key => :book_id,
:right_key => :student_id,
:join_table => :students_books
one_to_many :students_books, :key=>:student_id
end
class StudentsBook < Sequel::Model(:students_books)
many_to_one :book
many_to_one :student
end
现在您可以访问联结表中找到的任何列:
s1 = Student.create(:name => 'Hari')
b1 = Book.create(:title => 'Foundation')
s1.add_book(b1)
s1.students_books.first[:num_days_borrowed] = 10
s1.students_books.first.save
puts StudentsBook.first.inspect
#=> #<StudentsBook @values={:num_days_borrowed=>10, :student_id=>1, :book_id=>1}>
还要注意连接表和型号名称的复数化。当涉及到联结表时,它起初可能有点棘手。
答案 1 :(得分:1)
将one_to_many与连接模型一起使用是一种方法(如Threeve所述),但您也可以通过添加many_to_many books
选项与现有的:select=>[:books.*, :students_books__num_days_borrowed]
关联一起使用。然后在退回的图书实例上,使用book[:num_days_borrowed]
获取值