【问题标题】:Scala Slick 3.0.1 Relationship to selfScala Slick 3.0.1 与自我的关系
【发布时间】:2015-09-02 21:25:37
【问题描述】:

我有一个名为 Category 的实体,它与自身有关系。有两种类型的类别,父类别和子类别。子类别在 idParent 属性中具有来自父类别的 id。

我是这样定义架构的

class CategoriesTable(tag: Tag) extends Table[Category](tag, "CATEGORIES") {

  def id = column[String]("id", O.PrimaryKey)
  def name = column[String]("name")
  def idParent = column[Option[String]]("idParent")

  def * = (id, name, idParent) <> (Category.tupled, Category.unapply)
  def categoryFK = foreignKey("category_fk", idParent, categories)(_.id.?)
  def subcategories = TableQuery[CategoriesTable].filter(_.id === idParent)
}

我有这些数据:

   id      name      idParent
------------------------------
 parent   Parent
 child1   Child1      parent
 child2   Child2      parent

现在我想在按父类别分组的地图中获取结果,例如

地图( (parent,Parent,None) -> Seq[(child1,Child1,parent),(child2,Child2,parent] )

为此,我尝试了以下查询:

def findChildrenWithParents() = {
  db.run((for {
   c <- categories
   s <- c.subcategories
  } yield (c,s)).sortBy(_._1.name).result)
}

如果此时我执行查询:

categoryDao.findChildrenWithParents().map {
  case categoryTuples => categoryTuples.map(println _)
}

我明白了:

(Category(child1,Child1,Some(parent)),Category(parent,Parent,None))
(Category(child2,Child2,Some(parent)),Category(parent,Parent,None))

这里有两个事实已经让我感到不安:

  1. 它返回的是 Future[Seq[Category, Category]] 而不是我期望的 Future[Seq[Category, Seq[Category]]]。
  2. 顺序颠倒了,我希望父级首先出现:

    (Category(parent,Parent,None),Category(child1,Child1,Some(parent))) (Category(parent,Parent,None),Category(child2,Child2,Some(parent)))

现在我会尝试将它们分组。因为我在 Slick 中遇到嵌套查询问题。我对结果执行分组,如下所示:

categoryDao.findChildrenWithParents().map {
    case categoryTuples => categoryTuples.groupBy(_._2).map(println _)
}

但结果真的是一团糟:

(Category(parent,Parent,None),Vector((Category(child1,Child1,Some(parent)),Category(parent,Parent,None),(Category(child2,Child2,Some(parent)),Category(parent,Parent,None))))

我早就料到了:

(Category(parent,Parent,None),Vector(Category(child1,Child1,Some(parent)),Category(child2,Child2,Some(parent))))

你能帮我解决倒置结果和分组吗?

提前致谢。

【问题讨论】:

  • 我将子类别条件更改为: def subcategories = TableQuery[CategoriesTable].filter(c => id === c.idParent) 现在我只有在 Parent 上重复出现的问题按结果分组。谁能告诉我如何在分组后摆脱父母?

标签: scala slick slick-3.0


【解决方案1】:

好的,我自己解决了。如果有人想从中学习,这里是答案:

  def findChildrenWithParents() = {
    val result = db.run((for {
     c <- categories
     s <- c.subcategories
    } yield (c,s)).sortBy(_._1.name).result)

    result map {
      case categoryTuples => categoryTuples.groupBy(_._1).map{
        case (k,v) => (k,v.map(_._2))
      }
    }

  }

解决方案并不完美。我想通过已经在 Slick 中进行分组,但这会检索我想要的内容。

【讨论】:

  • 刚刚为这个albertoalmagro.com/en/scala-slick-3-relationship-to-self添加了后续帖子
  • 有类似的问题。然而,我的数据是树状的,而不是像你的 2 层。可悲的是,它不能通过 slick 完成,即使你的解决方案在我的情况下也行不通。我的解决方案是使用原生递归 SQL 语句(MySQL)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-03-08
  • 2012-12-10
  • 2018-04-24
  • 2021-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多