问题描述
select
*,(select count(1) from variants as v where v.product_id = p.id) as variants
from
products as p
;
该查询给出了我想要的结果,所以我现在只需要能够从Slick执行相同的操作即可。我有Product
和Variant
模型,并具有相应的Products
和Variants
表,并分别设置了products
和variants
TableQuery
。
这就是我最终得到的:
products.map(product =>
(product,variants.filter(_.productId === product.id).length)
) map (_ <> (ProductAndVariantCount.tupled,ProductAndVariantCount.unapply))
解决方法
基本形式为:
products.map(row =>
(row.id,row.otherColumnsHere,variants.filter(_.product_id === row.id).length)
)
我解决这些问题的方法是将查询的每个部分转换为Slick表达式,并查看它们如何组合。
您的情况是:
- 子选择类似于
table.filter(...).length
- 主要选择是
table.map(...)
- 然后看看我是否可以使它们以某种方式组合。