16

我最近问了一个类似的问题,并在使用 Lift Mapper 解决多对多关系问题上得到了很好的答复。我查看了ScalaQuery/SLICK 文档,但它没有记录涉及链接表的持久数据的方法。如果有人知道如何使用 SLICK 进行多对多映射,如果你能分享它会很棒。

4

1 回答 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 回答