문제

I have these tables: USERS, USER_ROLES, ROLES, PERMISSIONS, ROLE_PERMISSIONS

I am implementing the:

AssignedRoles (M): returns the set of roles assigned to a given user;

So, if I was going to write the query for this function it would like something like this:

SELECT role_id FROM USER_ROLES WHERE user_id = 'M'

where M is the given user id, then I would look up each role by their id and return the Role object, or I would use a join, but that is not relevant here.

so where is what my UserRole model looks like:

case class UserRole(id:Long, userID:Long, roleID:Long)
object UserRoles {
  class UserRoles(tag: Tag) extends Table[UserRole](tag, "USER_ROLES") {
    def id = column[Long]("ID", O.PrimaryKey, O.AutoInc)
    def userID = column[Long]("USER_ID")
    def roleID = column[Long]("ROLE_ID")

    def user = foreignKey("USER_ID", userID, TableQuery[Users])(_.id)
    def role = foreignKey("ROLE_ID", roleID, TableQuery[Roles])(_.id)

    def * = (id, userID, roleID) <> (UserRole.tupled, UserRole.unapply)
  }
  def retrieveRoles(userID:Long) : List[Role] = {
    DB.withSession { implicit session =>
      userRoles.filter(_.userID === userID).list
    }
  }

As expected retrieveRoles returns a list of UserRoles, but I want a list of Roles, so I woulds have to write another query that will take UserRole.roleID and find it in the roles table for each of UserRole that is returned. That is a lot of queries and I feel like there is a way that will to do this in one query. Any help from the Slick experts?

도움이 되었습니까?

해결책

userRoles.filter(_.userID === userID).flatMap(_.role)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top