我问过similar question recently, and got a great reply解决与Lift Mapper的多对多关系问题。我查看了ScalaQuery/SLICK documentation,但没有记录持久化涉及链接表的数据的方法。如果有人知道如何使用SLICK进行多对多映射,那么如果你可以分享它就会很棒。
答案 0 :(得分:23)
This test(由Stefan Zeiger创建)是SLICK测试套件中的新功能,可以很好地回答这个问题:
def testManyToMany(): Unit = db withSession {
object A extends Table[(Int, String)]("a") {
def id = column[Int]("id", O.PrimaryKey)
def s = column[String]("s")
def * = id ~ s
def bs = AToB.filter(_.aId === id).flatMap(_.bFK)
}
object B extends Table[(Int, String)]("b") {
def id = column[Int]("id", O.PrimaryKey)
def s = column[String]("s")
def * = id ~ s
def as = AToB.filter(_.bId === id).flatMap(_.aFK)
}
object AToB extends Table[(Int, Int)]("a_to_b") {
def aId = column[Int]("a")
def bId = column[Int]("b")
def * = aId ~ bId
def aFK = foreignKey("a_fk", aId, A)(a => a.id)
def bFK = foreignKey("b_fk", bId, B)(b => b.id)
}
(A.ddl ++ B.ddl ++ AToB.ddl).create
A.insertAll(1 -> "a", 2 -> "b", 3 -> "c")
B.insertAll(1 -> "x", 2 -> "y", 3 -> "z")
AToB.insertAll(1 -> 1, 1 -> 2, 2 -> 2, 2 -> 3)
/*val q1 = for {
a <- A if a.id >= 2
aToB <- AToB if aToB.aId === a.id
b <- B if b.id === aToB.bId
} yield (a.s, b.s)*/
val q1 = for {
a <- A if a.id >= 2
b <- a.bs
} yield (a.s, b.s)
q1.foreach(x => println(" "+x))
assertEquals(Set(("b","y"), ("b","z")), q1.list.toSet)
}
更新
我不太确定在Scala中集成业务逻辑和持久性的最佳方式是什么(因为这不仅仅是OO或FP),所以I asked a new question about this。希望这可以帮助那些对这个问题也很好奇的人。