Slick 3.1.x如何实现多对多连接?

时间:2016-12-05 09:47:33

标签: scala slick

UserDao我试图定义一个方法,给定用户将获得分配给它的所有安全角色。这是一个多对多的关系,这里是伪数据库设计(here is the actual Tables.scala full generated implementation):

User(PK id)
SecurityRole(PK id)
UserSecurityRole(
  userId FK to User(id), 
  securityRoleId FK to SecurityRole(id)
)

因此我尝试像这样定义getRoles函数:

def getRoles(user: UserRow) : Future[List[SecurityRoleRow]] = {
  val action = for {
  role <- SecurityRole join UserSecurityRole on (_.id === _.securityRoleId) 
            join User on (_.userId === _.id)
  } yield role
  db.run(action)
}

或者像这样:

def getRoles(user: UserRow) : Future[List[SecurityRoleRow]] = {
  val action = for {
    role <- SecurityRole join (UserSecurityRole join User on (_.userId === _.id)) on (_.id === _.securityRoleId)
  } yield role
  db.run(action)
}

但是在这两种情况下我都遇到编译器错误,can not resolve symbol _.userId注意输出必须是Role,因此,我用SecurityRole启动两个选项,因为它是&#39;我需要得到什么。我的印象是,在第一次加入之后,一些列被删除了,或者?

在SQL中,这将简单如下:

SELECT t1.*
FROM SecurityRole t1, 
     UserSecurityRole t2,
     User t3
WHERE t1.id = t2.securityRoleId
  AND t3.id = t2.userId

是的。然后,如果我想将这个SQL滑入我的UserDao我可以做:

def getRoles(user: UserRow) : Future[List[SecurityRoleRow]] = {
  val action = sql"""SELECT t1.* " +
                    "FROM SecurityRole t1, " + 
                         "UserSecurityRole t2, " +
                    "WHERE t1.id = t2.securityRoleId " +
                      "AND ${user.id} = t2.userId""".as[SecurityRoleRow]
    db.run(action)
}

0 个答案:

没有答案