0

我有一个 Liftweb 应用程序,我在其中使用 Record/Squeryl 作为 ORM 框架。这是我的架构:

object AppSchema extends Schema {
  import org.squeryl.dsl.OneToManyRelation

  val groups = table[Group]("groups")
  val domains = table[Domain]("domains")

  val groupToDomains =
    oneToManyRelation(groups, domains).
      via((g, d) => g.id === d.groupId)
}

object Group extends Group with MetaRecord[Group] with Loggable {

}

class Group extends Record[Group] with KeyedRecord[Long] with Loggable {
  override def meta = Group
  @Column(name = "id") override val idField = new LongField(this)
  val name = new StringField(this, 700, "")
  @Column(name = "date_added") val createdAt = new DateTimeField(this)

  lazy val domains: OneToMany[Domain] = AppSchema.groupToDomains.left(this)
}

object Domain extends Domain with MetaRecord[Domain] with Loggable {

}

class Domain extends Record[Domain] with KeyedRecord[Long] {
  override def meta = Domain

  @Column(name = "id") override val idField = new LongField(this)
  @Column(name = "group_id") val groupId = new LongField(this)
  val name = new StringField(this, 700, "")
  @Column(name = "date_added") val createdAt = new DateTimeField(this)

  lazy val group: ManyToOne[Group] = AppSchema.groupToDomains.right(this)  
}

我正在尝试实现一个计算组中域的函数:

def countDomainsInGroup(group: Group): Long = {
  val l = from(AppSchema.domains)(d => where(d.groupId === group.id) compute(count()))
  println("Count domains: " + l.statement)
  l.single.measures
}

这会生成以下 SQL:

Select
  count(*) as c0
From
  domains domains1
Where
  (domains1.group_id = 45)

现在一切正常,但我想应该有一个捷径,因为我们已经有了 group.domains,它定义了正确的 WHERE 语句。但是当我尝试像这样使用它时:

def countDomainsInGroup(group: Group): Long = {
  val l = from(group.domains)(d => compute(count()))
  println("Count domains: " + l.statement)
  l.single.measures
}

我得到以下 SQL 生成:

Select
  count(*) as c0
From
  (Select
     domains8.name as domains8_name,
     domains8.id as domains8_id,
     domains8.group_id as domains8_group_id,
     domains8.date_added as domains8_date_added,
   From
     domains domains8
   Where
     (45 = domains8.group_id)
  )  q1

可以看到,这里生成了一个子查询,我不需要。我究竟做错了什么?

4

1 回答 1

0

如果您仔细查看 OneToMany / ManyToOne,您会发现它们扩展了 Query。它们基本上是执行查询的便利,该查询通过主键检索与父或子相关的所有对象。如果你这样看,你看到的 SQL 就不足为奇了。您正在询问查询结果的计数,并且 Squeryl 在输出 SQL 时故意非常文字化,以便您可以自己优化事物而不必担心重写。如果子查询不是最优的,则没有理由必须计算关系的计数。

于 2013-11-27T17:19:56.413 回答