从这篇文章中汲取灵感:
How can I present a many-to-many relationship using a link table with ScalaQuery or 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)
// 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)
这不会尝试在aToC上为每个aToB进行子选择,因为这只是一个flatMap操作吗?