1
讓我說我有3個表:書,作者和BookAuthor。如何檢索與電梯的多對多關係數據
Book has id, title
Author has id, name
BookAuthor has id, book_id, author_id
我想查找一本書的所有作者。任何人都可以指導我如何用Lifts mapper語法來做到這一點?
讓我說我有3個表:書,作者和BookAuthor。如何檢索與電梯的多對多關係數據
Book has id, title
Author has id, name
BookAuthor has id, book_id, author_id
我想查找一本書的所有作者。任何人都可以指導我如何用Lifts mapper語法來做到這一點?
下面是書中的映射:
class Book extends LongKeyedMapper[Book] with IdPk with OneToMany[Long, Book] {
def getSingleton = Book
object title extends MappedString(this, 200)
object BookAuthor extends MappedOneToMany(BookAuthor, BookAuthor.id)
}
object Book extends Book with LongKeyedMetaMapper[Book]
的特質IdPk將書的ID的照顧。那麼對於BOOKAUTHOR:
class BookAuthor extends LongKeyedMapper[BookAuthor] with IdPk with OneToOne[Long, BookAuthor] {
def getSingleton = BookAuthor
object Author extends MappedOneToOne(Author, Author.id)
}
object BookAuthor extends BookAuthor with LongKeyedMetaMapper[BookAuthor]
然後作者,一個簡單的映射:
class Author extends LongKeyedMapper[Author] with IdPk {
def getSingleton = Author
object name extends MappedString(this, 200)
}
object Author extends Author with LongKeyedMetaMapper[Author]
然後打電話找一本書(這裏myBook
)的所有作者:
myBook.BookAuthor.map(x => x.Author.name)
如果您想要進行更復雜的加入請求而不必過濾Scala中的所有內容,您始終可以使用DB,並且您始終可以找到有關映射器的更多信息here 。
class Book extends LongKeyedMapper[Book]
with IdPK
with ManyToMany {
def getSingleton = Book
object title extends MappedString(this, 255)
object authors extends MappedManyToMany(
BookAuthors, BookAuthors.book, BookAuthors.author, Author)
}
object Book extends Book with LongKeyedMetaMapper[Book]
class Author extends LongKeyedMapper[Author]
with CreatedUpdated with IdPK
with ManyToMany {
def getSingleton = Author
object firstName extends MappedString(this, 255)
object lastName extends MappedText(this)
object email extends MappedEmail(this, 150)
object books extends MappedManyToMany(BookAuthors,
BookAuthors.author, BookAuthors.book, Book)
}
object Author extends Author with LongKeyedMetaMapper[Author]
val warandpeace = Book.create.title("War and Peace").saveMe
val fred = Author.create.firstName("Fred").saveMe
fred.books += warandpeace
fred.saveMe
val bob = Author.create.firstName("Bob").saveMe
bob.books += warandpeace
bob.saveMe
// then to find all the authors of the book:
val authors = warandpeace.authors
您在兩個實體上使用OneToMany,爲什麼?我有一個ManyToMany關係,我想我把它設置正確。問題只是如何讓一本書的所有作者都擁有該中間表的BookAuthor。順便說一句,什麼是班級音樂會? – user1243091 2012-03-30 15:55:01
嗨,我糾正了我有關「音樂會」,錯誤複製粘貼的錯誤。但是,有關更多詳細信息,您必須查看我在帖子中指定的mapper文檔。我想強調的重要事情是,您可以執行'myBook.BookAuthor'並獲取'BookAuthor'的列表。 – 2012-03-31 17:19:03
看起來這個段落可能會讓你感興趣:http://www.assembla.com/spaces/liftweb/wiki/Mapper#manytomany – 2012-03-31 20:20:59