我有一个 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
可以看到,这里生成了一个子查询,我不需要。我究竟做错了什么?