假设我有3个表:Book,Author和BookAuthor。
Book has id, title
Author has id, name
BookAuthor has id, book_id, author_id
我想找到一本书的所有作者。任何人都可以用Lifts mapper语法指导我如何做到这一点吗?
答案 0 :(得分: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
答案 1 :(得分: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将负责Book的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,并始终可以找到有关mapper here的更多信息。