1

Taking inspiration from this post:

How can I present a many-to-many relationship using a link table with ScalaQuery or SLICK?

My situation is a somewhat the same with some small exception.

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)

      // note I have another many-to-many join
      def cs = AtoC.filter(_cId === id).flatMap(_.aFK)
    }

    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)
    }

    object AToC extends Table[(Int, Int)]("a_to_c") {
      def aId = column[Int]("a")
      def cId = column[Int]("c")
      def * = aId ~ cId
      def aFK = foreignKey("a_fk", aId, A)(a => a.id)
      def cFK = foreignKey("c_fk", cId, C)(c => c.id)
    }
  }

Now when I want to fetch all A's by id, I would also want to fetch it associations in B and C, I would do something like:

    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)

How can I include the join to the C table? Is having something like this correct?

    for {
      a <- A if a.id >= 2
      aToB <- AToB if aToB.aId === a.id
      aToC <- AToC if aToC.aId === a.id
      b <- B if b.id === aToB.bId
      c <- C if c.id === aToC.cId
    } yield (a.s, b.s)

Wouldn't this try to do a sub-select on aToC for each aToB as this is just a flatMap operation?

Community
  • 1
  • 1
joesan
  • 13,963
  • 27
  • 95
  • 232

0 Answers0