【问题标题】:Inner join doesn't work in Slick内部联接在 Slick 中不起作用
【发布时间】:2013-05-23 06:51:07
【问题描述】:

你能告诉我为什么我没有得到我期望得到的内部加入吗?

我有以下表格

case class Ability(id: UUID, can: Boolean, verb: String, subject: String, context: String)

object Abilities extends Table[Ability]("abilities"){
  def id = column[UUID]("id", O.PrimaryKey)
  def can = column[Boolean]("is_can")
  def verb = column[String]("verb")
  def subject = column[String]("subject")
  def context = column[String]("context")

  def * = id ~ can ~ verb ~ subject ~ context <> (Ability, Ability.unapply _)
}

case class Role(id: UUID, name : String)

object Roles extends Table[Role]("roles"){
  def id = column[UUID]("id", O.PrimaryKey)
  def name = column[String]("name")

  def * = id ~ name <> (Role, Role.unapply _)
}

// And join table
case class AbilityRelationship(owner_id: UUID, obj_id: UUID, is_role: Boolean)

object AbilitiesMapping extends Table[AbilityRelationship]("abilities_mapping"){
  def owner_id = column[UUID]("owner_id")
  def obj_id = column[UUID]("obj_id")
  def is_role = column[Boolean]("is_role")

  def * = owner_id ~ obj_id ~ is_role <> (AbilityRelationship, AbilityRelationship.unapply _)
}

我愿意做的是获取特定所有者(无论是用户还是角色)的Ability 对象列表。因此,按照文档,我为它编写了以下连接查询

val some_id = role.id
val q2 = for {
  a <- Abilities
  rel <- AbilitiesMapping
  if rel.owner_id === some_id.bind
} yield (a)

但是q2.selectStatement 会返回绝对错误的查询。在我的情况下是select x2."id", x2."is_can", x2."verb", x2."subject", x2."context" from "abilities" x2, "abilities_mapping" x3 where x3."owner_id" = ?

应该如何实现?

谢谢。

【问题讨论】:

    标签: scala scala-2.10 slick


    【解决方案1】:

    好吧,经过多次尝试,我成功了

      val innerJoin = for {
        (a, rel) <- Abilities innerJoin AbilitiesMapping on (_.id === _.obj_id) if rel.owner_id === some_id.bind
      } yield a
    

    但是人... typesafe 的文档对于新手来说真的很弱。

    【讨论】:

    • 重要的是使用 if 而不是将其添加到 on 条件
    【解决方案2】:

    尝试类似:

    val q2 = for {
      a <- Abilities
      rel <- AbilitiesMapping
      if a.id == rel.obj_id && rel.owner_id === some_id.bind
    } yield (a)
    

    顺便说一句,您知道您可以在 Table 对象中注释外键吗?

    【讨论】:

    • 但就我而言,我不需要来自Role 的任何信息。我在some_id 中有它的 ID。
    • 现在我明白你想要什么了。我将重写我的查询。
    • 是的,我可以注释外键,但我不确定在我的情况下使用 Slick 是否可以这样做,因为外键可能会根据 is_role 引用不同的对象。
    【解决方案3】:

    尝试这样做作为对鲁斯兰回答的评论,但我只是没有足够的绝地力量:

    你可以试试这个脱糖版本是否有效?

    val rightSide = AbilitiesMapping.filter(_.owner_id === some_id)    
    val innerJoin = (Abilities innerJoin (rightSide) on (
      (l,r) => (l.id === r.obj_id)
    ).map { case (l, r) => l }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-13
      • 1970-01-01
      • 1970-01-01
      • 2011-03-11
      • 2011-12-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多