12

我正在尝试使用 Slick 来查询多对多关系,但我遇到了各种错误,最突出的是“不知道如何将 (User, Skill) 解压到 T 并打包到G”。

表的结构类似于以下内容:

case class User(val name: String, val picture: Option[URL], val id: Option[UUID])
object Users extends Table[User]("users") {
  def name = column[String]("name")
  def picture = column[Option[URL]]("picture")
  def id = column[UUID]("id")
  def * = name ~ picture ~ id.? <> (User, User.unapply _)
}

case class Skill(val name: String, val id: Option[UUID])
object Skills extends Table[Skill]("skill") {
  def name = column[String]("name")
  def id = column[UUID]("id")
  def * = name ~ id.? <> (Skill, Skill.unapply _)
}

case class UserSkill(val userId: UUID, val skillId: UUID, val id: Option[UUID])
object UserSkills extends Table[UserSkill]("user_skill") {
  def userId = column[UUID]("userId")
  def skillId = column[UUID]("skillId")
  def id = column[UUID]("id")
  def * = userId ~ skillId ~ id.? <> (UserSkill, UserSkill.unapply _)
  def user = foreignKey("userFK", userId, Users)(_.id)
  def skill = foreignKey("skillFK", skillId, Skills)(_.id)
}

最终,我想要实现的是某种形式

SELECT u.*, group_concat(s.name) FROM user_skill us, users u, skills s WHERE us.skillId = s.id && us.userId = u.id GROUP BY u.id

但在我花时间尝试让 group_concat 也能正常工作之前,我一直在尝试生成更简单的查询(我相信它仍然有效......)

SELECT u.* FROM user_skill us, users u, skills s WHERE us.skillId = s.id && us.userId = u.id GROUP BY u.id

我已经尝试了各种 scala 代码来生成这个查询,但是导致上面形状错误的一个例子是

(for {
  us <- UserSkills
  user <- us.user
  skill <- us.skill
} yield (user, skill)).groupBy(_._1.id).map { case(_, xs) => xs.first }

同样,以下会产生关于“用户”而不是“(用户,技能)”的打包错误

(for {
  us <- UserSkills
  user <- us.user
  skill <- us.skill
} yield (user, skill)).groupBy(_._1.id).map { case(_, xs) => xs.map(_._1).first }

如果有人有任何建议,我将不胜感激:我今天和昨天大部分时间都在搜索 google/google 组以及 slick 源,但我还没有解决方案。

(另外,我使用的是 postgre,所以 group_concat 实际上是 string_agg)

编辑

所以看起来当使用 groupBy 时,映射的投影被应用,因为像

(for {
  us <- UserSkills
  u   <- us.user
  s   <- us.skill
} yield (u,s)).map(_._1)

工作正常,因为 _._1 给出了用户类型,它有一个形状,因为用户是一个表。然而,当我们调用 xs.first 时(就像我们调用 groupBy 时所做的那样),我们实际上得到了一个映射的投影类型 (User, Skill),或者如果我们先应用 map(_._1),我们得到了 User 类型,这不是用户!据我所知,没有 User 作为混合类型的形状,因为定义的唯一形状是用于 Shape[Column[T], T, Column[T]] 和表 T <: TableNode, Shape[T , NothingContainer#TableNothing, T] 在 slick.lifted.Shape 中定义。此外,如果我做类似的事情

(for {
  us <- UserSkills
  u   <- us.user
  s   <- us.skill
} yield (u,s))
  .groupBy(_._1.id)
  .map { case (_, xs) => xs.map(_._1.id).first }

我收到“NoSuchElementException:找不到键:@1515100893”形式的奇怪错误,其中数字键值每次都会更改。这不是我想要的查询,但它仍然是一个奇怪的问题。

4

2 回答 2

1

我也遇到过类似的情况。虽然我喜欢使用 Scala 和 Slick,但我确实相信有时更容易对数据库本身中的对象进行非规范化并将 Slick 表链接到视图。

例如,我有一个应用程序,它有一个 Tree 对象,该对象被规范化为几个数据库表。因为我对 SQL 很熟悉,所以我认为它比编写普通的 Scala Slick 查询更简洁。斯卡拉代码:

case class DbGFolder(id: String,
                     eTag: String,
                     url: String,
                     iconUrl: String,
                     title: String,
                     owner: String,
                     parents: Option[String],
                     children: Option[String],
                     scions: Option[String],
                     created: LocalDateTime,
                     modified: LocalDateTime)
object DbGFolders extends Table[DbGFolder]("gfolder_view") {
  def id = column[String]("id")
  def eTag = column[String]("e_tag")
  def url = column[String]("url")
  def iconUrl = column[String]("icon_url")
  def title = column[String]("title")
  def owner = column[String]("file_owner")
  def parents = column[String]("parent_str")
  def children = column[String]("child_str")
  def scions = column[String]("scion_str")
  def created = column[LocalDateTime]("created")
  def modified = column[LocalDateTime]("modified")
  def * = id ~ eTag ~ url ~ iconUrl ~ title ~ owner ~ parents.? ~
          children.? ~ scions.? ~ created ~ modified <> (DbGFolder, DbGFolder.unapply _)

  def findAll(implicit s: Session): List[GFolder] = {
    Query(DbGFolders).list().map {v =>
      GFolder(id = v.id,
              eTag = v.eTag,
              url = v.url,
              iconUrl = v.iconUrl,
              title = v.title,
              owner = v.owner,
              parents = v.parents.map { parentStr =>
                parentStr.split(",").toSet }.getOrElse(Set()),
              children = v.children.map{ childStr =>
                childStr.split(",").toSet }.getOrElse(Set()),
              scions = v.scions.map { scionStr =>
                scionStr.split(",").toSet }.getOrElse(Set()),
              created = v.created,
              modified = v.modified)
    }
  }
}

以及底层(postgres)视图:

CREATE VIEW scion_view AS
    WITH RECURSIVE scions(id, scion) AS (
      SELECT c.id, c.child
      FROM children AS c
      UNION ALL
      SELECT s.id, c.child
      FROM children AS c, scions AS s
      WHERE c.id = s.scion)
    SELECT * FROM scions ORDER BY id, scion;    

CREATE VIEW gfolder_view AS
  SELECT
    f.id, f.e_tag, f.url, f.icon_url, f.title, m.name, f.file_owner,
    p.parent_str, c.child_str, s.scion_str, f.created, f.modified
  FROM
    gfiles AS f
      JOIN mimes AS m ON (f.mime_type = m.name)
      LEFT JOIN (SELECT DISTINCT id, string_agg(parent, ',' ORDER BY parent) AS parent_str
                 FROM parents GROUP BY id) AS p ON (f.id = p.id)
      LEFT JOIN (SELECT DISTINCT id, string_agg(child, ',' ORDER BY child) AS child_str
                 FROM children GROUP BY id) AS c ON (f.id = c.id)
      LEFT JOIN (SELECT DISTINCT id, string_agg(scion, ',' ORDER BY scion) AS scion_str
                 FROM scion_view GROUP BY id) AS s ON (f.id = s.id)
  WHERE
    m.category = 'folder';
于 2013-10-13T05:26:17.307 回答
1

尝试这个。希望它会产生你所期望的结果。在案例类下方找到 Slick Code。

单击此处 获取有关提升嵌入的参考。

case class User(val name: String, val picture: Option[URL], val id: Option[UUID])
            class Users(_tableTag: Tag) extends Table[User](_tableTag,"users") {
              def name = column[String]("name")
              def picture = column[Option[URL]]("picture")
              def id = column[UUID]("id")
              def * = name ~ picture ~ id.? <> (User, User.unapply _)
            }
             lazy val userTable = new TableQuery(tag => new Users(tag))

            case class Skill(val name: String, val id: Option[UUID])
            class Skills(_tableTag: Tag) extends Table[Skill](_tableTag,"skill") {
              def name = column[String]("name")
              def id = column[UUID]("id")
              def * = name ~ id.? <> (Skill, Skill.unapply _)
            }
             lazy val skillTable = new TableQuery(tag => new Skills(tag))

            case class UserSkill(val userId: UUID, val skillId: UUID, val id: Option[UUID])
            class UserSkills(_tableTag: Tag) extends Table[UserSkill](_tableTag,"user_skill") {
              def userId = column[UUID]("userId")
              def skillId = column[UUID]("skillId")
              def id = column[UUID]("id")
              def * = userId ~ skillId ~ id.? <> (UserSkill, UserSkill.unapply _)
              def user = foreignKey("userFK", userId, Users)(_.id)
              def skill = foreignKey("skillFK", skillId, Skills)(_.id)
            }
             lazy val userSkillTable = new TableQuery(tag => new UserSkills(tag))






(for {((userSkill, user), skill) <- userSkillTable join userTable.filter on
                    (_.userId === _.id) join skillTable.filter on (_._1.skillId === _.id)
                } yield (userSkill, user, skill)).groupBy(_.2.id)
于 2015-02-12T13:39:58.597 回答