right usage of slick filter

非 Y 不嫁゛ 提交于 2019-12-06 05:33:01

问题


I'm using slick to access database. I want to query like this:

case class Coupon(couponId: Long, shopId: String)

class Coupons(tag: Tag) extends Table[Coupon](tag, "coupons"){

  def couponId = column[Long]("coupon_id")

  def shopId = column[String]("shop_id")

  override def * = (couponId, shopId) <> (Coupon.tupled, Coupon.unapply)
}

object Coupons extends TableQuery(new Coupons(_)){

  def findCouponBy(couponId: Long, shopId: Option[String]) = {

    val s = DB.createSession()
    try {
       val q = for {
           coupon <- this.filter(c => c.couponId === couponId && 
                shopId.map(s => c.shopId === s).getOrElse(true)
        } yield coupon
      s.database.run(q.result)
    } finally s.close
  }
}

I thought this might work. However, the compiler tells me that Error:(126, -1) Play 2 Compiler: type mismatch; found : Any required: slick.lifted.Rep[?]

Problem lies on here: shopId.map(s => c.shopId === s).getOrElse(true)

I'm wondering how I can make this work.

I'm using slick 3.0.0-RC


回答1:


Use slick.lifted.LiteralColumn(true)

Scala's type infer limitation




回答2:


As it is mentioned in this answer, you can use the following API since Slick 3.3.0:

def findCouponBy(couponId: Long, shopId: Option[String]) = {
  val query = 
    this
      .filter(_.couponId === couponId)
      .filterOpt(shopId){ case (table, sid) =>
        table.filter(_.shopId === sid)
      }

  db run query.result
}


来源:https://stackoverflow.com/questions/30090872/right-usage-of-slick-filter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!