right usage of slick filter
Asked Answered
M

2

4

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

Marianomaribel answered 7/5, 2015 at 2:22 Comment(0)
F
2

Use slick.lifted.LiteralColumn(true)

Scala's type infer limitation

Funches answered 7/5, 2015 at 3:50 Comment(3)
And I was wondering that, I want to take this out as a method: shopId.map(s => c.shopId === s).getOrElse(true) as def checkCondition[T](column: Rep[T], parameter:T) = { column === parameter } Is there a way to make it through?Marianomaribel
parameter: Rep[T] or maybe checkCondition[T:TypedType] or checkcondition[T:BaseTypedType]Funches
there's a little hook on the left of the answerFunches
I
1

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
}
Ible answered 9/7, 2019 at 15:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.