我试图弄清楚如何将我自己的闭包表实现从另一种语言移植到 Scala,同时考虑到并发性。
我有两个模型,一个节点(id | parentID)和一个 NodeTree(id | 祖先 | 后代),其中每个条目都类似于树中的一条边。
对于每个新节点,我必须执行以下操作:查询所有祖先(或为它们过滤 TableQuery),然后为每个祖先添加一个 NodeTree-Entry(一条边)
感谢黑豹,我走到了这一步:
private val nodes = TableQuery[Nodes]
override def create(node: Node): Future[Seq[Int]] =
{
val createNodesAction = (
for
{
parent <- nodes
node <- (nodeTrees returning nodeTrees.map(_.id) into ((ntEntry, ntId) => ntEntry.copy(id = Some(ntId))) += NodeTree(id = None, ancestor = parent.id, descendant = node.id, deleted = None, createdAt = new Timestamp(now.getTime), updatedAt = new Timestamp(now.getTime)))
} yield (node)
).transactionally
db run createNodesAction
}
但这会导致类型不匹配;
类型不匹配; 找到:slick.lifted.Rep[Long] 需要:Option[Long]
再一次:我想要做的是:对于每个 parentNode(= 每个父节点的父节点,直到最后一个祖先节点没有父节点!)我想在 nodeTree 中创建一个条目,以便稍后我可以轻松地获取所有后代和祖先只需另一个通过 NodeTree-Table 过滤的方法调用。
(只是一个封闭表,真的)
编辑:这些是我的模型
case class Node(id: Option[Long], parentID: Option[Long], level: Option[Long], deleted: Option[Boolean], createdAt: Timestamp, updatedAt: Timestamp)
class Nodes(tag: Tag) extends Table[Node](tag, "nodes")
{
implicit val dateColumnType = MappedColumnType.base[Timestamp, Long](d => d.getTime, d => new Timestamp(d))
def id = column[Long]("id", O.PrimaryKey, O.AutoInc)
def parentID = column[Long]("parent_id")
def level = column[Long]("level")
def deleted = column[Boolean]("deleted")
def createdAt = column[Timestamp]("created_at")
def updatedAt = column[Timestamp]("updated_at")
def * = (id.?, parentID.?, level.?, deleted.?, createdAt, updatedAt) <> (Node.tupled, Node.unapply)
}
case class NodeTree(id: Option[Long], ancestor: Option[Long], descendant: Option[Long], deleted: Option[Boolean], createdAt: Timestamp, updatedAt: Timestamp)
class NodeTrees(tag: Tag) extends Table[NodeTree](tag, "nodetree")
{
implicit val dateColumnType = MappedColumnType.base[Timestamp, Long](d => d.getTime, d => new Timestamp(d))
def id = column[Long]("id", O.PrimaryKey, O.AutoInc)
def ancestor = column[Long]("ancestor")
def descendant = column[Long]("descendant")
def deleted = column[Boolean]("deleted")
def createdAt = column[Timestamp]("created_at")
def updatedAt = column[Timestamp]("updated_at")
def * = (id.?, ancestor.?, descendant.?, deleted.?, createdAt, updatedAt) <> (NodeTree.tupled, NodeTree.unapply)
}
我想要做的是一个闭包表(http://technobytz.com/closure_table_store_hierarchical_data.html),当我创建一个节点时它会自动填充它的边缘(nodeTree)。所以我不想手动将所有这些条目添加到数据库中,但是当我在第 5 级创建节点时,我希望自动创建整个路径(= nodetree-table 中的条目)。
我希望这能澄清一些事情:)