“In” clause in anorm?

前端 未结 7 820
轮回少年
轮回少年 2020-12-30 23:53

It seems no easy way to use \"in\" clause in anorm:

val ids = List(\"111\", \"222\", \"333\")
val users = SQL(\"select * from users where id in ({ids})\").on         


        
7条回答
  •  自闭症患者
    2020-12-31 00:05

    It's probably late, but I add this for others looking for the same. You could use some built-in database features to overcome this. This is one of the advantages Anorm has over ORMs. For example, if you are using PostgreSQL you could pass your list as an array and unnest the array in your query:

    I assume ids are integer.

    val ids = List(1, 2, 3)
    
    val idsPgArray = "{%s}".format(ids.mkString(",")) //Outputs {1, 2, 3}
    
    val users = SQL(
      """select * from users where id in (select unnest({idsPgArray}::integer[]))"""
    ).on('ids-> ???).as(parser *)
    

    Executed query will be

    select * from users where id in (select unnest('{1, 2, 3}'::integer[])) 
    

    which is equal to

    select * from users where id in (1, 2, 3)
    

提交回复
热议问题