Scala Slick 3.1多个连接

时间:2016-04-05 08:02:00

标签: scala slick

我试图在Slick 3.1.1中执行多个连接。我想要实现的结果是:

SELECT * FROM customer LEFT JOIN customer_address ON customer.id = customer_address.customer_id LEFT JOIN address ON customer_address.address_id = address.id

我尝试了以下内容:

val query = for {
  c <- Customer
  ca <- CustomerAddress if ca.customerId === c.id
  a <- Address if a.id === ca.addressId
} yield (c, a)

这里的问题是,如果客户没有一个没有意义的地址。

然后我尝试了这个:

    val query2 = for {
       (c, ca, a) <- (Customer joinLeft CustomerAddress on (_.id === _.customerId)) joinLeft Address on (_._2.addressId === _.id)
    } yield (c, a)

此处的问题是我在_._2.addressId上收到错误,因为_._2Rep个对象。

确切错误:

Error:(21, 110) value addressId is not a member of slick.lifted.Rep[Option[Models.Tables.CustomerAddress]]
  (c, ca, a) <- (Customer joinLeft CustomerAddress on (_.id === _.customerId)) joinLeft Address on (_._2.addressId === _.id)

自动生成的Slick Tables类: http://pastebin.com/e4M3cGU8

如何通过Slick获得我想要的结果?

3 个答案:

答案 0 :(得分:5)

您需要做的就是映射结果。

val query2 = for {
      ((c, ca), a) <- (Customer joinLeft CustomerAddress on (_.id === _.customerId)) joinLeft Address on (_._2.map(_.addressId) === _.id)
} yield (c, a)

答案 1 :(得分:1)

这应该有效。 // ((c, ca), a)而不是(c, ca, a)

val query2 = for {
   ((c, ca), a) <- (Customer joinLeft CustomerAddress on (_.id === _.customerId)) joinLeft Address on (_._2.addressId === _.id)
} yield (c, a)

答案 2 :(得分:1)

这个答案也和其他答案一样,但是更加清晰和可读。

val query2 = for {
    ((customer, customerAddress), address) <-
        (Customer joinLeft CustomerAddress on
            {
                case(customerTable,customerAddressTable) =>
                    (customerTable.id === customerAddressTable.customerId)
            }
        ) joinLeft Address on
            {
                case ((customerTable,customerAddressTable),addressTable) =>
                    (customerAddressTable.map(_.addressId) === addressTable.id)
            }
} yield (customer, address)