SLICK:如何在另一个查询中使用查询结果?

时间:2014-04-22 00:49:59

标签: scala playframework-2.0 slick play-slick slick-2.0

我想执行以下操作:

我想返回一个用户列表,该用户列表首先由用户是谁"在"后面排序,然后是一些额外的点数。 我编写的下面的代码不起作用,因为资助者是提升的Slick类型,因此从未在列表中找到。

        //The following represents the query for only funders who we are following
        val following_funders:  List[User]  = (
            for {
          funder <- all_funders
          f <- follows if f.followerId === id //get all the current users follower objects
          if f.followeeId === funder.id
        } yield funder
        ).list

      val all_funders_sorted = for {
        funder <- all_funders
        following_funder =  following_funders contains funder
      } yield (funder, following_funder)
      //sort the funders by whether or not they are following the funder and then map it to only the funders (i.e. remove the boolean)
      all_funders_sorted.sortBy(_._2.desc).sortBy(_._1.score.desc).map( x => x._1 )  

所有帮助表示赞赏!

2 个答案:

答案 0 :(得分:3)

您需要在Slick中使用ID(即主键)。这就是db方面唯一标识对象的方式。您不需要执行第一个查询。您可以使用它作为第二个组件,而不是先使用in运算符执行它:

    //The following represents the query for only funders who we are following
    val following_funders_ids = (
        for {
      funder <- all_funders
      f <- follows if f.followerId === id //get all the current users follower objects
      if f.followeeId === funder.id
    } yield funder.id

  val all_funders_sorted = for {
    funder <- all_funders
    following_funder = funder.id in following_funders_ids
  } yield (funder, following_funder)
  //sort the funders by whether or not they are following the funder and then map it to only the funders (i.e. remove the boolean)
  all_funders_sorted.sortBy(_._1.impactPoints.desc).sortBy(_._2.desc).map( x => x._1 )   

如果您想首先按照排序排序,请注意排序顺序错误。 Slick会将.sortBy(_.a).sortBy(_.b)翻译为ORDER BY B,A,因为这就是Scala集合的工作方式:

scala> List( (1,"b"), (2,"a") ).sortBy(_._1).sortBy(_._2)
res0: List[(Int, String)] = List((2,a), (1,b))

答案 1 :(得分:-1)

通过使用&#39; inSet&#39;

,结束以下方式计算出来
        //The following represents the query for only funders who we are following
        val following_funders_ids:  List[Long]  = (
            for {
          funder <- all_funders
          f <- follows if f.followerId === id //get all the current users follower objects
          if f.followeeId === funder.id
        } yield funder.id
        ).list
      val all_funders_sorted = for {
        funder <- all_funders
        following_funder = funder.id inSet following_funders_ids
      } yield (funder, following_funder)
      //sort the funders by whether or not they are following the funder and then map it to only the funders (i.e. remove the boolean)
      all_funders_sorted.sortBy(_._2.desc).sortBy(_._1.impactPoints.desc).map( x => x._1 )