2012-03-30 63 views
1

让我说我有3个表:书,作者和BookAuthor。如何检索与电梯的多对多关系数据

Book has id, title 
Author has id, name 
BookAuthor has id, book_id, author_id 

我想查找一本书的所有作者。任何人都可以指导我如何用Lifts mapper语法来做到这一点?

回答

0

下面是书中的映射:

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

+0

您在两个实体上使用OneToMany,为什么?我有一个ManyToMany关系,我想我把它设置正确。问题只是如何让一本书的所有作者都拥有该中间表的BookAuthor。顺便说一句,什么是班级音乐会? – user1243091 2012-03-30 15:55:01

+0

嗨,我纠正了我有关“音乐会”,错误复制粘贴的错误。但是,有关更多详细信息,您必须查看我在帖子中指定的mapper文档。我想强调的重要事情是,您可以执行'myBook.BookAuthor'并获取'BookAuthor'的列表。 – 2012-03-31 17:19:03

+0

看起来这个段落可能会让你感兴趣:http://www.assembla.com/spaces/liftweb/wiki/Mapper#manytomany – 2012-03-31 20:20:59

2
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 
相关问题