sql - squeryl: how to use oneToMany relation for constructing queries -
i have liftweb application in use record/squeryl orm framework. here schema:
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 metarecord[group] loggable { } class group extends record[group] keyedrecord[long] 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 metarecord[domain] loggable { } class domain extends record[domain] 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) }
i'm trying implement function counts domains in group:
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 }
this generates following sql:
select count(*) c0 domains domains1 (domains1.group_id = 45)
now ok that, suppose there should shortcut, have group.domains, has proper statement defined. when try use this:
def countdomainsingroup(group: group): long = { val l = from(group.domains)(d => compute(count())) println("count domains: " + l.statement) l.single.measures }
i following sql generated:
select count(*) c0 (select domains8.name domains8_name, domains8.id domains8_id, domains8.group_id domains8_group_id, domains8.date_added domains8_date_added, domains domains8 (45 = domains8.group_id) ) q1
as can see, subquery generated here, don't need. doing wrong?
if take closer @ onetomany / manytoone, you'll see extend query. convenience executing query retrieves of objects related parent or child primary key. if @ way, sql see isn't surprising. asking count of results of query, , squeryl purposely pretty literal when outputting sql can optimize things without worrying rewriting. if subquery isn't optimal, there no reason why have compute count on relation.
Comments
Post a Comment