Reputation: 1101
I want to create a query that returns all groups with users count (including empty groups)
SELECT g.id, count(relation.user_id) FROM groups g
FULL JOIN users2groups relation ON g.id=r.group_id
GROUP BY g.id;
for this model:
class Users(tag: Tag) extends Table[User](tag, "users") {
def id = column[Long]("id", O.PrimaryKey, O.AutoInc)
...
}
class Groups(tag: Tag) extends Table[Group](tag, "groups") {
def id = column[Long]("id", O.PrimaryKey, O.AutoInc)
...
}
val users = TableQuery[Users]
val groups = TableQuery[Groups]
/** relation for users and group */
class Users2Groups(tag: Tag) extends Table[(Long,Long)](tag, "users2groups") {
def userId = column[Long]("user_id")
def groupId = column[Long]("group_id")
def user = foreignKey("user_fk", userId, users)(_.id)
def group = foreignKey("group_fk", groupId, groups)(_.id)
def * = (userId, groupId)
def ? = (userId.?, groupId.?)
def pk = primaryKey("pk_user2group", (userId, userId))
}
This is my solution with slick:
val query = for {
(g, rel) <-
groups leftJoin
users2groups on (_.id === _.groupId)
} yield (g, rel.groupId.?)
val result = query.groupBy(_._1.id).map(e => (e._1, e._2.length)).list
result foreach println
But it doesn't work correctly. It returns the incorrect amount of users for empty groups (returns users count = 1 instead of 0).
My environment: scala-2.11.2, slick-2.1.0, PostgreSQL
Upvotes: 0
Views: 472
Reputation: 11270
I don't see what's wrong. Could well be a Slick bug. Please report one here: https://github.com/slick/slick
Upvotes: 1