最近、同様の質問をしたところ、Lift Mapper を使用して多対多の関係の問題を解決する素晴らしい回答が得られました。ScalaQuery/SLICKのドキュメントを見ましたが、リンク テーブルが関係するデータを永続化する方法については記載されていません。誰かが SLICK を使用して多対多のマッピングを行う方法を知っている場合は、共有していただければ幸いです。
4301 次
1 に答える
23
このテスト(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 を超えるものであるため) はよくわからないので、これについて新しい質問をしました。これが、この問題に興味を持っている他の誰かに役立つことを願っています.
于 2012-07-18T12:52:58.523 に答える