我将如何使用 Slick 中的子选择执行此 SQL 查询?

How would I perform this SQL query with subselect in Slick?

select
    *,
    (select count(1) from variants as v where v.product_id = p.id) as variants
from
    products as p
;

查询给出了我想要的结果,所以我现在只需要能够从 Slick 执行相同的操作。我有 ProductVariant 模型以及相应的 ProductsVariants 表以及 productsvariants 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 表达式,然后看看它们如何组合。

在你的例子中,想法是:

  • sub-select 类似于 table.filter(...).length
  • 主要select是table.map(...)
  • 然后看看我能否让它们以某种方式结合起来。